Sub topic 3
How with works: __enter__ and __exit__
This chapter assumes you can write Python classes with special methods, and that you know how try/except/finally behaves. It also assumes you have used with open(...). Generators and decorators are not needed here.
The earlier chapters showed why with exists and how it reads. This chapter covers the machinery under it: the two methods that make an object a context manager, the order in which Python calls them, and the places where people's mental model of with goes wrong.
The protocol in one sentence
An object is a context manager if its class defines __enter__ and __exit__. The with statement calls __enter__ before the block runs. It calls __exit__ after the block finishes, however it finishes.
| Method | Called | Receives | Return value is used for |
|---|---|---|---|
| `__enter__(self)` | Once, before the block | Nothing besides `self` | The name after `as` |
| `__exit__(self, exc_type, exc_value, traceback)` | Once, after the block | Exception details, or three `None` values | Deciding whether to suppress an exception |
A manager that narrates itself
The fastest way to learn the protocol is to watch it run. This class prints every call it receives.
class Trace:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"enter {self.name}")
return self
def __exit__(self, exc_type, exc_value, traceback):
print(f"exit {self.name}: {exc_type}")
return False
with Trace("a") as t:
print("body", t.name)The output is:
enter a
body a
exit a: NoneWhen the block finishes normally, __exit__ receives None for all three exception arguments. Now raise inside the block:
try:
with Trace("b"):
raise ValueError("boom")
except ValueError as e:
print("caught", e)The output is:
enter b
exit b: <class 'ValueError'>
caught boom__exit__ runs first and sees the exception type. Because it returns False, the exception continues past the with statement and the outer except catches it. The cleanup has already happened by then.
What Python actually executes
The with statement is defined by PEP 343 as roughly the following expansion. The function below runs as written and mimics the real statement.
import sys
def run_with(manager, body):
exit_ = type(manager).__exit__
value = type(manager).__enter__(manager)
try:
body(value)
except BaseException:
if not exit_(manager, *sys.exc_info()):
raise
else:
exit_(manager, None, None, None)
run_with(Trace("c"), lambda t: print("body", t.name))Several details of the real statement are visible in this sketch.
- The expression is evaluated once.
with Trace("c")creates one object, and that same object receives both calls. __exit__is looked up before__enter__runs. If the object has no__exit__, the statement fails before any setup happens.- Both methods are looked up on the type. Python does not read them from the instance.
- The
astarget receives the return value of__enter__. It does not receive the manager. __exit__gets the exception, and its return value decides the outcome. A false value means "re-raise". A true value means "I handled it, continue after the block".
The real statement catches BaseException, not just Exception. KeyboardInterrupt, SystemExit and GeneratorExit all pass through __exit__. That is what lets a lock be released when the user presses Ctrl+C.
The ordering is summarized below.
The as clause binds the return value of __enter__
Beginners often assume with X() as name makes name the manager. It only does when __enter__ returns self, which is common but not required.
class Greeter:
def __enter__(self):
return "hello"
def __exit__(self, exc_type, exc_value, traceback):
return None
with Greeter() as g:
print(g, type(g).__name__)This prints hello str. The name g holds a string, and the Greeter object is only reachable through the with machinery.
This is deliberate and useful. decimal.localcontext() returns a copy of the current context for you to modify. Many database and lock managers return a connection or a handle instead of themselves. If a manager's documentation does not say what as gives you, check what __enter__ returns.
If __enter__ returns None, which is what happens when you forget a return, then as name quietly binds None. The error shows up later as AttributeError: 'NoneType' object has no attribute ....
The as part is optional. with lock: is common because the lock itself is the only thing you need. The target can also be any assignment target, so with open(p) as self.file: and tuple unpacking both work.
When __exit__ does and does not run
The guarantee is precise, and its edges matter.
__exit__ runs after the block ends for any of these reasons:
- The block finishes normally.
- The block raises any exception, including
KeyboardInterrupt. - The block runs
return,breakorcontinue.
For the last case, __exit__ receives three None values, because no exception is in flight:
def read_first():
with Trace("r"):
return "result"
print(read_first())The output is:
enter r
exit r: None
result__exit__ does not run in two situations.
If __enter__ raises, the block never started, so there is nothing to clean up. Python does not call __exit__:
class Broken:
def __enter__(self):
raise RuntimeError("cannot start")
def __exit__(self, exc_type, exc_value, traceback):
print("exit called")
try:
with Broken():
print("never printed")
except RuntimeError as e:
print(e)This prints only cannot start. The consequence is that __enter__ must clean up after itself if it fails halfway. Suppose it opens two files and the second open fails. It has to close the first before letting the error escape, because no __exit__ call will do it.
The second situation is a hard process kill, such as os._exit() or SIGKILL. Python never gets a chance to run any code. The guarantee covers Python-level control flow only.
Errors in the protocol itself
An object that lacks one of the methods is rejected before the block runs. On Python 3.11 and later the error is a TypeError. Earlier versions raise AttributeError.
Because Python looks the methods up on the type, attaching them to an instance does not work:
class Plain:
pass
p = Plain()
p.__enter__ = lambda: p
p.__exit__ = lambda *args: None
try:
with p:
pass
except (TypeError, AttributeError) as e:
print(type(e).__name__)This prints TypeError on Python 3.11 and later. Python treats special methods this way throughout the language. len(obj) and obj + 1 also ignore instance attributes. To change what a manager does, subclass it or pass configuration to its constructor.
Writing __exit__ safely
Four rules prevent most bugs in __exit__.
- Return a false value unless you mean to suppress. Falling off the end of the function returns
None, which is false, so most managers need no explicit return. Writingreturn Falsemakes the intent visible. - Do not re-raise the exception that was passed in. Returning false already tells Python to propagate it. Raising it again adds a confusing traceback frame.
- Be careful about raising a new exception. If
__exit__raises while another exception is in flight, the new exception replaces the old one. Python attaches the original as__context__, so it is still visible in the traceback. Cleanup code that can fail, such as a flush or a network close, should not hide the error from the block. - Do not return a true value by accident. Writing
return self.close()is risky ifclose()returns something truthy. That silently swallows every exception from the block.
The three arguments, briefly
When the block raises, __exit__ receives the exception class, the exception instance and the traceback object. On a clean exit all three are None, so exc_type is None is the standard test for "no error occurred".
That test is how a manager chooses between two actions. A transaction manager, for example, commits when exc_type is None and rolls back otherwise. Here it is in miniature:
class Transaction:
def __init__(self):
self.log = []
def __enter__(self):
self.log.append("begin")
return self
def __exit__(self, exc_type, exc_value, traceback):
self.log.append("commit" if exc_type is None else "rollback")
return False
ok = Transaction()
with ok:
pass
bad = Transaction()
try:
with bad:
raise KeyError("x")
except KeyError:
pass
print(ok.log)
print(bad.log)The output is:
['begin', 'commit']
['begin', 'rollback']The KeyError still reaches the outer try, because __exit__ returned False. The manager reacted to the failure without deciding whether it counted as handled.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `as` name is `None` | `__enter__` has no `return` | Add `return self` |
| `__exit__` never ran after a failed setup | The error came from `__enter__` | Clean up inside `__enter__` before re-raising |
| Exceptions vanish | `__exit__` returns a truthy value | Return `False` or `None` unless you handled the error |
| `TypeError` about the context manager protocol | A method is missing or defined on the instance | Define both methods on the class |
| Using the `as` name after the block shows a closed resource | The name stays bound after the block | Treat the value as unusable after exit |
The last row is easy to miss. with does not create a scope, so the as variable survives the block, but the resource behind it has already been released.
Summary
with EXPR as NAME: evaluates EXPR once, calls __enter__ on its type, and binds the return value to NAME. It then runs the block and always calls __exit__ with either exception details or three None values. The return value of __exit__ decides whether an exception continues. A failure inside __enter__ skips __exit__ entirely. Knowing this sequence lets you predict what any context manager does, including the ones you write in the next chapters.
Exercise
What does this program print, and in what order? Explain why __exit__ is or is not called in each case.
class M:
def _init(self, name, failenter=False):
self.name = name
self.failenter = failenter
def _enter(self):
print("enter", self.name)
if self.failenter:
raise RuntimeError("no")
return self.name.upper()
def _exit(self, exctype, excvalue, traceback):
print("exit", self.name, exctype is None)
return False
with M("x") as v:
print("got", v)
try:
with M("y", fail_enter=True) as v:
print("unreachable")
except RuntimeError:
print("caught")
Show answer
The output is: enter x, got X, exit x True, enter y, caught. In the first case the block finishes normally, so __exit__ runs with no exception and exc_type is None is True. The name v is "X" because __enter__ returns the uppercased name, not the manager. In the second case __enter__ raises before the block starts, so Python never calls __exit__ for y, and the RuntimeError goes straight to the outer except.
Exercise
A teammate writes def __exit__(self, *args): return self.connection.close(), and close() returns True on success. What goes wrong, and how do you fix it?
Show answer
Because close() returns a true value, __exit__ returns true on every exit, so any exception raised in the block is suppressed and the program continues as if nothing happened. The fix is to call self.connection.close() as a statement and then return False (or return nothing).