Code

Context Managers from Generators

Writing a class for every context manager is a bit heavy. The contextlib.contextmanager decorator turns a generator into one:

from contextlib import contextmanager

@contextmanager
def shout():
    print("BEGIN")       # like __enter__
    try:
        yield "megaphone"  # value for `as`
    finally:
        print("END")     # like __exit__

with shout() as m:
    print("using", m)

Everything before the yield is the setup, the yielded value goes to as, and everything after is the cleanup.

If the with block raises, the exception pops out at the yield. Without try/finally, your cleanup would be skipped! Always wrap the yield in try/finally when cleanup must happen.

Assignment

Write borrowed(settings, key, value), a context manager that temporarily changes one entry in the settings dict:

  1. On entry, remember the old value, set settings[key] = value, and yield value.
  2. On exit, put the old value back, even if an error happened.
  3. If key wasn't in settings to begin with, delete it on exit instead.