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 those chapters skip: what happens when the same manager object is used more than once, or used inside itself.
Three kinds of manager
A context manager object falls into one of three categories:
| Kind | Can it be used in a second `with`? | Can it be used inside its own `with` block? |
|---|---|---|
| Single-use | No | No |
| Reusable | Yes, after the first block ends | No |
| Reentrant | Yes | Yes (nested) |
Every reentrant manager is also reusable. The reverse is not true.
Single-use managers
A manager is single-use when entering it consumes something that cannot be recreated. Two common examples:
- File objects. After the first
withblock closes the file, entering it again raisesValueError: I/O operation on closed file. - Managers built with
@contextmanager. The object wraps one generator, and a generator runs only once.
from contextlib import contextmanager
@contextmanager
def tag():
print("setup")
yield
print("teardown")
cm = tag()
with cm:
pass
try:
with cm:
pass
except Exception:
print("second use failed")The exact exception type depends on the Python version, so don't rely on it. The fix is to call the decorated function again for each block: with tag():. Each call builds a fresh generator.
Reusable managers
A reusable manager keeps no state that blocks a second entry. Each __enter__ fully sets up, and each __exit__ fully tears down. threading.Lock is reusable: you can acquire and release it any number of times in sequence. It is not reentrant. If a thread holds the lock and enters with lock: again, it waits for itself and deadlocks.
Reentrant managers
A reentrant manager can be entered again while an earlier with on the same object is still active. It must track nesting, usually with a counter or a stack, so the inner exit does not undo the outer setup.
class Section:
def __init__(self, name):
self.name = name
self.depth = 0
def __enter__(self):
self.depth += 1
print(f"enter {self.name} (depth {self.depth})")
return self
def __exit__(self, exc_type, exc_value, traceback):
print(f"exit {self.name} (depth {self.depth})")
self.depth -= 1
return False
s = Section("db")
with s:
with s:
pass
with s:
passThe counter returns to 0 after the nested blocks, so the third with starts clean. The standard library has examples of both properties:
contextlib.suppressandcontextlib.redirect_stdoutare reentrant.threading.RLockis the reentrant version ofLock.contextlib.ExitStackis reusable but not reentrant.
How state on `self` breaks reentrancy
The Timer from the class-based chapter stores self.start. That works for sequential reuse, since each __enter__ overwrites the old value. It breaks when nested:
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.elapsed = time.perf_counter() - self.start
return False
t = Timer()
with t:
with t:
pass
# t.start now belongs to the inner blockThe inner __enter__ overwrote start, so the outer block's elapsed time is measured from the wrong moment. To make this class reentrant, push each start time onto a list in __enter__ and pop it in __exit__. Keeping state in a stack is the usual pattern.
Summary of the decision
Prefer single-use or reusable managers for simplicity. Add reentrancy only when the same object must be shared, such as a lock or a global setting that nested code may re-enter.
Exercise
A class-based manager sets self.old = os.getcwd() in __enter__ and calls os.chdir(self.old) in __exit__. Is it safe to nest with m: inside with m: on the same object? Why or why not?
Show answer
No. The inner __enter__ overwrites self.old with the directory the outer block already changed to. When the inner block exits it restores that directory, and when the outer block exits it restores the same value again, so the original directory is never restored. Storing the old directories in a list (push in __enter__, pop in __exit__) makes it reentrant.