Track 12 · Lesson 7 of 12
Context managers
Guarantee clean-up with the with statement: write __enter__ and __exit__, handle exceptions in __exit__, and use contextlib.contextmanager and suppress.
You will be able to
- Explain what the with statement guarantees and when __enter__ and __exit__ run
- Write a context manager class, including what __enter__ returns
- Decide in __exit__ whether an exception is suppressed or propagates
- Write a context manager as a generator with contextlib.contextmanager
- Use contextlib.suppress for an expected, harmless exception
Included with a Formula Quest membership
It has 4 graded exercises with feedback, hints and solutions. Python Quest is included in Formula Quest memberships that cover Python; membership and billing are managed on Formula Quest.
View Formula Quest memberships
Tracks 1 and 2, the first lesson of every track, the playground and the dataset library are free.