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
open()returns a context manager whose `__exit__` closes the file handle even if the code inside the
withblock raises an exception halfway through.