Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Errors & context managersMiddleVery commonTheory

What methods does a class need to support the `with` statement, and what do their return values control?

Answer

A context manager implements `__enter__`, which runs when the `with` block is entered and whose return value is bound to the `as` variable, and `__exit__(self, exc_type, exc_value, traceback)`, which always runs when the block exits, whether it exited normally or because of an exception. If an exception occurred, `__exit__` receives its details and can suppress it by returning a truthy value; returning `None` or a falsy value lets the exception propagate normally after cleanup runs. This guarantees cleanup code runs even when the block raises, unlike a plain try/finally that a caller might forget to write.

Strong answer includes

  • __enter__ return value binds to the as variable
  • __exit__ always runs, receives exception details if any occurred
  • returning truthy from __exit__ suppresses the exception

Practical example

The built-in

Python example
open()

returns a context manager whose `__exit__` closes the file handle even if the code inside the

Python example
with

block raises an exception halfway through.

#context-managers#with-statement

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocolscontextlib — Utilities for with-statement contextsPython Software Foundation · Context manager helpers, including contextmanager and ExitStack