Module lessons (3/4)
Context managers: with and __enter__/__exit__
with open(...), custom __enter__/__exit__ protocols, @contextmanager, and contextlib.suppress.
What you'll learn in this lesson
- Ensure deterministic acquisition and release of resources via the
withconstruct. - Implement class-based context managers with
__enter__and__exit__. - Write concise generator-based context managers with
@contextmanagerandtry ... finally:block. - Use built-in
contextlibutilities likesuppress()to handle expected exceptions cleanly.
Overview
Open files, network connections, inter-thread locks, and database transactions must always be closed at the end of use, even if an exception pops in the middle. The context managers (the with instruction) automate the cleanup phase by ensuring closure is performed at the end of the block.
Behind the scenes with ctx as val: calls ctx.__enter__() first (binding the return value to as val) and at the end of the block — whether exiting normally or due to an error — always calls ctx.__exit__(exc_type, exc_val, exc_tb).
Sections covered in this lesson
- 11. Complete protocol
__enter__and__exit__ - 22. The
@contextmanagerdecorator withtry ... finally - 33. Suppress expected exceptions with
contextlib.suppress - 44. Compose multiple context managers into a single
with - 5Check for understanding
- 6Test yourself
Unlock "Context managers: with and __enter__/__exit__" and the full Python Course curriculum
with open(...), custom __enter__/__exit__ protocols, @contextmanager, and contextlib.suppress.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.