×

python · level 3 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

turns a generator into a context manager.

A whole class is a lot of typing for set-up and clean-up. The module has a shortcut: put @contextmanager above a generator that yields exactly once.

Everything before the yield is the set-up, and whatever you yield is caught by as. Everything after the yield is the clean-up, which runs when the block ends.

Put the yield inside try and the clean-up inside finally. Then the clean-up runs even if the block crashes, as __exit__ does.

from contextlib import contextmanager
settings = {"theme": "light"}
@contextmanager
def temporary(key, value):
    old = settings[key]
    settings[key] = value
    try:
        yield settings
    finally:
        settings[key] = old

with temporary("theme", "dark") as s:
    print("inside:", s["theme"])
print("after:", settings["theme"])

contextlib also has suppress, so with suppress(FileNotFoundError): ignores that one error inside the block.