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

  1. remove_quietly(items, item): remove item from the list items with items.remove(item), using suppress(ValueError) so a missing item is ignored. Return items.
  2. light_all(names, log): use an ExitStack to enter torch(name, log) (provided) for every name, then append "all lit" to log. For ["a", "b"] the log becomes ["light a", "light b", "all lit", "snuff b", "snuff a"].