▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Context managers
How with works, and writing your own.
🎬 Video version coming soon — read it now
You've used with open(...) since the files course. That with statement works with any context manager: an object that sets something up, and guarantees cleanup afterwards, even if an error happens.
What with really does
is roughly:
The with version is shorter and impossible to get wrong.
Where context managers appear
- Files:
open - Locks in threaded code:
with lock: - Database connections and transactions
- Temporary folders:
tempfile.TemporaryDirectory() - Suppressing an expected error:
contextlib.suppress
Writing one with a class
Implement __enter__ and __exit__:
__exit__ receives details of any exception. Returning False lets it continue upwards, which is almost always what you want.
The easy way: contextlib.contextmanager
Everything before yield is setup; everything after, in finally, is cleanup. This combines a generator and a decorator, two lessons in one.
Handy built-ins
Several context managers can share one with.
In one line
Context managers guarantee cleanup with the with statement; write them with __enter__/__exit__ or, more simply, @contextmanager and yield.
Share with a friend