Skip to main content
Module 9 · Lesson 3 of 435/36 in the course~16 min
Module lessons (3/4)

Context managers: with and __enter__/__exit__

Lesson preview5 hands-on exercises readyPython Course · Module 9 — Modern Python in practice

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 with construct.
  • Implement class-based context managers with __enter__ and __exit__.
  • Write concise generator-based context managers with @contextmanager and try ... finally: block.
  • Use built-in contextlib utilities like suppress() 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

  1. 11. Complete protocol __enter__ and __exit__
  2. 22. The @contextmanager decorator with try ... finally
  3. 33. Suppress expected exceptions with contextlib.suppress
  4. 44. Compose multiple context managers into a single with
  5. 5Check for understanding
  6. 6Test yourself
Pro Lesson · Module 9 — Modern Python in practice

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.