
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:
- On entry, remember the old value, set
settings[key] = value, and yieldvalue. - On exit, put the old value back, even if an error happened.
- If
keywasn't insettingsto begin with, delete it on exit instead.
Write borrowed(settings, key, value), a context manager that temporarily
changes one entry in the settings dict:
- On entry, remember the old value, set
settings[key] = value, and yieldvalue. - On exit, put the old value back, even if an error happened.
- If
keywasn't insettingsto begin with, delete it on exit instead.
main.py Python sleeping
Press Run to try your code, then Check to test it.