Sub topic 11
Single-use, reusable, and reentrant managers
This chapter assumes you can write class-based managers with __enter__ and __exit__, and generator-based managers with @contextmanager. It covers a question both styles raise: what happens when the same manager object is used in a second with statement, or in a with statement nested inside its own block?
Three properties of a manager object
A context manager is an object, and objects keep state. Whether that state survives a with block decides how safely the object can be used again. There are three levels:
- Single-use: the object works for one
withstatement. After__exit__runs, it is spent. Entering it again fails or misbehaves. - Reusable: the object can be used in many
withstatements, one after another. Each__enter__starts from a clean state. - Reentrant: the object can be entered again while it is already active, as in
with cm:nested insidewith cm:. Every__exit__undoes exactly the matching__enter__.
The levels build on each other. A reentrant manager is also reusable, and a reusable manager is not necessarily reentrant.
None of these properties is a flaw. They are part of a manager's contract, and you should know which one each manager gives you before sharing it.
Generator-based managers are single-use
An object created by @contextmanager wraps one generator. The generator runs from its start to its yield on enter, and from the yield to its end on exit. A finished generator cannot be restarted, so the object can run only once.
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f"<{name}>")
try:
yield
finally:
print(f"</{name}>")
cm = tag("b")
with cm:
print("text")
try:
with cm:
print("again")
except (RuntimeError, AttributeError) as exc:
print("cannot reuse:", type(exc).__name__)
with tag("b"):
print("fresh object works")The second with cm: fails before its body runs. The exact exception type depends on the Python version, which is why the example catches both. The fix is to call tag("b") again, because each call builds a new generator and a new manager object.
Because of this, a function decorated with @contextmanager is best thought of as a factory for single-use managers. It is a normal pattern to call it inline: with tag("b"):. The problem only appears when you store the result in a variable and use it twice.
Other single-use managers in everyday code include file objects. After with open(...) as f: finishes, the file is closed. Writing with f: again raises ValueError because __enter__ refuses a closed file.
Making a class-based manager reusable
A class-based manager is reusable if __enter__ fully initializes whatever __exit__ later reads, and __exit__ leaves nothing behind that would confuse the next entry. The Timer from earlier chapters already works this way. Each __enter__ overwrites self.start, and each __exit__ overwrites self.elapsed.
Reuse in sequence is safe, but one detail needs attention. Attributes such as elapsed hold the result of the last run only. If you need results from earlier runs, copy them out before the next with statement starts.
The rule for reusable managers is to put per-run state in __enter__, not in __init__. Put only configuration, which does not change between runs, in __init__.
Why a reusable manager may not be reentrant
Reentrancy adds a harder requirement. Entering twice means two activations are alive at once, but a plain attribute can hold only one value. Here is a manager that changes the working directory, written the obvious way.
import os
import tempfile
class ChangeDir:
def __init__(self, path):
self.path = path
def __enter__(self):
self.previous = os.getcwd()
os.chdir(self.path)
def __exit__(self, exc_type, exc_value, traceback):
os.chdir(self.previous)
return False
original = os.getcwd()
with tempfile.TemporaryDirectory() as tmp:
cd = ChangeDir(tmp)
with cd:
with cd:
pass
print("restored:", os.getcwd() == original)
os.chdir(original) # clean up so the temp directory can be removedThis prints restored: False. Here is the sequence:
- The outer
__enter__stores the original directory inself.previousand moves intotmp. - The inner
__enter__overwritesself.previouswithtmp, because that is now the current directory. - The inner
__exit__changes totmp. - The outer
__exit__also changes totmp, since the original directory is gone.
The manager is reusable, because sequential with statements work, but it is not reentrant. The fix is to keep a stack of saved values, one per active entry.
import os
import tempfile
class ChangeDir:
def __init__(self, path):
self.path = path
self._previous = []
def __enter__(self):
self._previous.append(os.getcwd())
os.chdir(self.path)
def __exit__(self, exc_type, exc_value, traceback):
os.chdir(self._previous.pop())
return False
original = os.getcwd()
with tempfile.TemporaryDirectory() as tmp:
cd = ChangeDir(tmp)
with cd:
with cd:
pass
print("inside outer:", os.getcwd() == os.path.realpath(tmp))
print("restored:", os.getcwd() == original)Now each __exit__ pops the value that its own __enter__ pushed, and the output ends with restored: True. Since Python 3.11 the standard library provides contextlib.chdir, which works this way. The class here shows the technique.
A counter works for state that only needs to be incremented and decremented, and no stack is needed.
class Indent:
def __init__(self):
self.level = 0
def __enter__(self):
self.level += 1
return self
def __exit__(self, exc_type, exc_value, traceback):
self.level -= 1
return False
def say(self, text):
print(" " * self.level + text)
indent = Indent()
with indent:
indent.say("a")
with indent:
indent.say("b")
indent.say("c")
indent.say("d")The output is a indented by two spaces, b by four, c by two, and d by none. The counter is reentrant because every enter and exit pair is balanced, and the value after the inner block is the same as before it.
Making a single-use manager reusable and reentrant
You cannot change a @contextmanager function to be reusable, but you can wrap it. The wrapper stores the factory and its arguments, builds a fresh single-use manager on every entry, and keeps the active ones on a stack.
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f"<{name}>")
try:
yield
finally:
print(f"</{name}>")
class Reusable:
def __init__(self, factory, *args):
self._factory = factory
self._args = args
self._active = []
def __enter__(self):
cm = self._factory(*self._args)
value = cm.__enter__()
self._active.append(cm)
return value
def __exit__(self, exc_type, exc_value, traceback):
return self._active.pop().__exit__(exc_type, exc_value, traceback)
section = Reusable(tag, "section")
with section:
with section:
print("nested")
with section:
print("again")The wrapper passes the exception details through to the inner manager and returns its answer. Suppression and propagation therefore behave exactly as they would without the wrapper. This is the same idea the standard library uses. For example, redirect_stdout keeps a stack of saved targets so that nested uses restore the right one.
What the standard library promises
The contextlib documentation describes the standard managers in these terms. Check the documentation of any manager you share between callers, because the property is part of its documented behavior.
| Manager | Single-use | Reusable | Reentrant |
|---|---|---|---|
| `@contextmanager` result | Yes | No | No |
| File object from `open()` | Yes | No | No |
| `threading.Lock` | No | Yes | No |
| `threading.RLock` | No | Yes | Yes |
| `contextlib.suppress` | No | Yes | Yes |
| `contextlib.redirect_stdout` | No | Yes | Yes |
| `contextlib.ExitStack` | No | Yes | No |
The lock rows matter most in practice. Calling with lock: while the same thread already holds a plain Lock blocks forever, because the second __enter__ waits for a release that only the first block can perform. RLock counts the acquisitions per thread, so the nested entry succeeds. Use RLock when a function that holds the lock may call another function that takes the same lock.
ExitStack is reusable but not reentrant. Leaving any with block that uses it runs every callback registered so far, regardless of which block registered them. A nested entry of the same stack would therefore close resources that the outer block still needs.
Reentrancy and decorators
Managers built on contextlib.ContextDecorator, and results of @contextmanager, can also be applied as function decorators. Each call to the decorated function enters the manager again. For generator-based managers, contextlib recreates the generator on every call, so decorated functions work, including when they call themselves.
A class-based manager used as a decorator through ContextDecorator is different. By default, every call reuses the same instance. If the decorated function is recursive, or if two threads call it at once, the instance is entered several times at once. It must then be reentrant, and for threads it must also protect its own state. If you cannot guarantee that, override _recreate_cm to return a fresh copy per call.
Choosing a design
Decide what your manager promises and then make the code match.
- Prefer single-use when state is naturally tied to one block, such as an open connection or a temporary directory. Document that callers should create a new object per
withstatement. - Choose reusable when the manager holds only configuration, such as a path or a name. Initialize per-run state in
__enter__. - Choose reentrant when callers may nest the same object, which is common for locks, indentation, and temporary overrides. Use a stack or counter for per-entry state.
- When a single-use manager must be shared, hand out the factory, such as
tag, and not the manager object.
Checking your understanding
Exercise
A function decorated with @contextmanager returns an object stored in the variable cm. Using with cm: twice in a row fails the second time. Give two ways to fix it.
Show answer
Call the decorated function again for each with statement (for example, with tag("b"): each time), or wrap the factory in a reusable class that builds a fresh manager on every _enter_ and keeps the active ones on a stack.
Exercise
In the first ChangeDir, nesting the same instance leaves the process in the wrong directory. Which line causes it, and why does a list fixes the problem?
Show answer
The line self.previous = os.getcwd() in _enter overwrites the original directory with the inner entry's value. A list stores one saved directory per active entry, and each exit pops the value its own enter_ pushed.
Exercise
Why does with lock: nested twice in one thread hang for threading.Lock but work for threading.RLock?
Show answer
Lock is reusable but not reentrant, so the second _enter_ waits for a release that only the blocked thread could perform. RLock counts acquisitions per thread, so the nested entry succeeds and the lock is released when the outermost block exits.