
Code
suppress and ExitStack
contextlib has two more handy tools.
suppress: ignore one specific error
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove("old_map.txt")
This is a short way of writing try: ... except FileNotFoundError: pass.
If the error happens, the rest of the block is skipped and the program carries
on after the with.
ExitStack: a dynamic number of context managers
with a, b, c: only works when you know how many you need. If the number
depends on data, use an ExitStack:
from contextlib import ExitStack
with ExitStack() as stack:
files = [stack.enter_context(open(name)) for name in names]
... # all files open here
# all files closed here, in reverse order
stack.enter_context(cm) enters cm and returns what its __enter__ gave.
When the with ExitStack() block ends, everything is exited in reverse order.
Assignment
remove_quietly(items, item): removeitemfrom the listitemswithitems.remove(item), usingsuppress(ValueError)so a missing item is ignored. Returnitems.light_all(names, log): use anExitStackto entertorch(name, log)(provided) for every name, then append"all lit"tolog. For["a", "b"]the log becomes["light a", "light b", "all lit", "snuff b", "snuff a"].
remove_quietly(items, item): removeitemfrom the listitemswithitems.remove(item), usingsuppress(ValueError)so a missing item is ignored. Returnitems.light_all(names, log): use anExitStackto entertorch(name, log)(provided) for every name, then append"all lit"tolog. For["a", "b"]the log becomes["light a", "light b", "all lit", "snuff b", "snuff a"].
main.py Python sleeping
Press Run to try your code, then Check to test it.