Sub topic 3
How with works: __enter__ and __exit__
This chapter assumes you know Python classes and methods, try/except/finally, and basic file handling with open(). You have seen that with closes a file for you. Here you will see the mechanism behind it.
The context manager protocol
A context manager is any object that defines two special methods:
__enter__(self)runs when thewithblock starts. Its return value is bound to the name afteras.__exit__(self, exc_type, exc_value, traceback)runs when the block ends, whether it ended normally or with an exception.
Together these two methods are the context manager protocol. Python does not check for a base class. It only looks for the two methods on the object's type.
What Python does for you
Take this statement:
with EXPR as VAR:
BODYPython roughly treats it as the following steps:
- Evaluate
EXPRto get the context manager object. - Look up
__enter__and__exit__on its type. - Call
__enter__()and assign the result toVAR. - Run
BODY. - Call
__exit__()howeverBODYfinished.
If BODY finishes normally, __exit__ receives None, None, None. If BODY raises, it receives the exception type, the exception instance, and the traceback.
Watching the protocol run
The easiest way to learn the order of events is to print from each method.
class Trace:
def __enter__(self):
print("enter")
return "value from enter"
def __exit__(self, exc_type, exc_value, traceback):
print("exit", exc_type)
return False
with Trace() as v:
print("body sees:", v)
print("after with")The output is:
enter
body sees: value from enter
exit None
after withNow make the body fail:
class Trace:
def __enter__(self):
print("enter")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("exit", exc_type.__name__ if exc_type else None)
return False
try:
with Trace():
1 / 0
except ZeroDivisionError:
print("caught outside")The output is:
enter
exit ZeroDivisionError
caught outside__exit__ ran before the outer except. Because it returned False, the exception continued to propagate.
The as clause is not the manager
The name after as receives whatever __enter__ returns. That is often the manager itself, but it does not have to be. open() returns the file object from __enter__, which is the same object. Other managers return something different, such as a database cursor or a path.
class Greeting:
def __enter__(self):
return "hello"
def __exit__(self, *args):
return False
with Greeting() as g:
print(g) # hello, a str, not a GreetingIf __enter__ has nothing useful to return, it returns None, and you leave off as.
Equivalent try/finally
The with statement behaves like a try/finally that is written once, in the object, instead of at every call site. The sketch below shows the idea. The real rules are in the Python language reference.
manager = Trace()
value = manager.__enter__()
try:
pass # body
finally:
manager.__exit__(None, None, None)Note that __enter__ is called before the try. If __enter__ itself raises, __exit__ is not called, because setup never completed. Put any cleanup for a half-finished setup inside __enter__.
Common errors
- Missing method. Using an object without both methods raises
TypeError(orAttributeErrorin Python 3.10 and earlier). The message names the missing method. - Wrong signature.
__exit__must accept three arguments afterself. Writingdef __exit__(self):fails whenwithends. - Returning a truthy value by accident. Any true return value from
__exit__suppresses the exception. A forgottenreturngivesNone, which is safe. Returning something like a non-empty string orTruehides errors. The next chapter covers this in detail. - Expecting
__exit__after a failed__enter__. It does not run, as shown above.
Exercise
A class defines __enter__ that raises RuntimeError on its first line. Is its __exit__ method called? Why or why not?
Show answer
No. Python calls __exit__ only after __enter__ returns successfully, because the block is considered started only then. Any cleanup needed for a partly finished setup must be done inside __enter__ itself, for example with its own try/except.
Exercise
In with Greeting() as g: where __enter__ returns the string "hello", what is g, and what object does Python call __exit__ on?
Show answer
g is the string "hello", the value returned by __enter__. Python calls __exit__ on the Greeting instance, the object that the expression after with produced.