You already know how to create and use context managers. This last article gathers the habits that avoid mistakes and several real examples from the standard library.
1. Use with whenever there is something to release
If an object has close(), a lock, a connection or a temporary folder, the right thing is a with. Never depend on "remembering" to close it.
2. Several managers in the same with
They are separated by commas. They are opened from left to right and closed from right to left.
from contextlib import contextmanager
@contextmanager
def resource(name):
print("open", name)
try:
yield name
finally:
print("close", name)
with resource("input") as source, resource("output") as target:
print(f"copying from {source} to {target}")
# open input
# open output
# copying from input to output
# close output
# close input
It is what you will see in Guaranteed cleanup. If the number of managers is not fixed, use ExitStack.
3. Do not suppress errors without thinking
Returning True in __exit__ (or writing an except without re-raising inside a @contextmanager) hides the failure. Limit it to specific errors, and if possible report what happened (with a message or a log).
4. Always restore the state
If your manager changes something (a setting, a working directory, the decimal precision), it must put it back to its original value in the finally. This is how the standard library does it:
from decimal import Decimal, localcontext
print(Decimal(1) / Decimal(7)) # 0.1428571428571428571428571429
with localcontext() as ctx:
ctx.prec = 4
print(Decimal(1) / Decimal(7)) # 0.1429
print(Decimal(1) / Decimal(7)) # 0.1428571428571428571428571429
It is the idea of Temporary setting.
5. A manager can decide according to the error
__exit__ receives the class of the error, so it can log, undo or suppress only certain cases. See Transaction with rollback and Error-aware log.
6. The value of as can be the manager itself
When the manager stores data (a list of notes, a counter), return self in __enter__ to use it inside and also after the block.
class Counter:
def __init__(self):
self.operations = 0
def __enter__(self):
return self
def __exit__(self, *args):
return False
def add(self, a, b):
self.operations += 1
return a + b
with Counter() as c:
c.add(1, 2)
c.add(3, 4)
print(c.operations) # 2 (the object is still available)
Checklist
- Is there a resource to open and close, or a state to change and restore? →
with. - Is it short and linear? →
@contextmanagerwithtry/finally. Does it need state or to decide according to the error? → class. - Variable number of resources? →
ExitStack. - Ignoring an error? →
suppress(SpecificError), only if it is correct. - Testing a function that prints? →
redirect_stdout.
There is also async with for asynchronous code, with the same idea, which you will see when you study asynchronous programming.