Context managers
A context manager is an object that sets something up, yields it to a with block, and tears it down afterwards. Files, locks, and database connections are context managers so cleanup cannot be forgotten.
Detailed Explanation
with is the statement. The context manager is the object that makes the statement useful. Any object that implements __enter__ and __exit__ qualifies. __enter__ runs at the start and its return value is bound to as. __exit__ runs at the end with three arguments: the exception type, the exception value, and the traceback, or three Nones if the block succeeded.
__exit__ returning a true value swallows the exception. Returning False or None lets it propagate. Almost every context manager should return False. Swallowing is for helpers whose whole job is to suppress a type, such as contextlib.suppress(FileNotFoundError).
The protocol exists because try / finally is easy to get slightly wrong. You can forget finally. You can return from try and skip a close you put on the next line. You can handle an exception and then forget that the file is still open. __exit__ is the finally that the object carries with it.
contextlib.contextmanager lets you write the same protocol as a generator. The code before yield is __enter__. The yielded value is the as target. The code after yield is __exit__. A try / finally around yield is the usual form so cleanup runs on error. This is the fastest way to wrap a setup/teardown pair that is not worth a class.
contextlib.asynccontextmanager and __aenter__ / __aexit__ are the async versions, used with async with. The event loop must be running; a normal with will not await them.
ExitStack (and AsyncExitStack) opens a dynamic number of context managers and guarantees they all close in reverse order. Use it when the set of files or locks is not known until runtime.
Reentrancy is not free. A lock that is not reentrant will deadlock if you with it twice on the same thread. A file object can be used as a context manager once per open. Check the object's docs before nesting.
Code Examples
from pathlib import Path
path = Path("access.log")
path.write_text("ok\n", encoding="utf-8")
with path.open(encoding="utf-8") as log:
print(log.read().strip()) # ok
# log is closed here, even if read() had raisedfrom contextlib import contextmanager
@contextmanager
def temp_flag(store: dict, key: str, value: str):
previous = store.get(key)
store[key] = value # setup
try:
yield store[key] # bound to `as`
finally:
if previous is None:
store.pop(key, None) # teardown
else:
store[key] = previous
flags = {}
with temp_flag(flags, "env", "test") as current:
print(current, flags) # test {'env': 'test'}
print(flags) # {}class Closer:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
print("closed", exc_type)
return False # do not swallow
with Closer():
pass # closed NoneCommon Gotchas
Returning `True` from `__exit__` swallows the error
the `with` block looks like it succeeded. Return `False` unless suppression is the documented purpose.
`@contextmanager` must yield exactly once
zero yields or two yields break the protocol. Put cleanup in `finally` after the single `yield`.
`async with` is required for async managers
using `with` on them raises `TypeError`. The opposite is also true.
The `as` name is whatever `__enter__` returns
it is often `self`, but a file returns the file, and a lock may return `None`. Do not assume.