The context manager protocol consists of two dunder methods: __enter__() and __exit__(). Any object that implements both methods can be used with the with statement. __enter__() is called when entering the with block, and its return value is bound to the variable after as. __exit__(exc_type, exc_val, exc_tb) is called when leaving the block, receiving exception information if an exception occurred (or None values if the block completed normally).
If __exit__ returns a truthy value, the exception is suppressed (swallowed). If it returns a falsy value (the default), the exception propagates normally. This mechanism lets context managers handle errors — for example, a database transaction context manager might commit on normal exit and roll back on exception.
The contextlib module provides shortcuts for creating context managers without writing a class. The @contextmanager decorator turns a generator function into a context manager: code before yield is the __enter__, the yielded value is the as target, and code after yield is the __exit__. This is often more concise than writing a class, especially for simple setup/teardown patterns.
Related terms: Context Manager, Dunder Method
Discussed in:
- Chapter 17: Decorators, Generators, and Iterators — Context Managers with @contextmanager