Writing a class with two methods is a lot of code for something simple. The contextlib module offers the @contextmanager decorator, which turns a generator function with a single yield into a context manager.
How to write it
What goes before the yield is the entry; what goes after is the exit. What you put in the yield is the value for as.
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f"<{name}>")
try:
yield
finally:
print(f"</{name}>")
with tag("p"):
print("text")
# <p>
# text
# </p>
Returning a value
from contextlib import contextmanager
@contextmanager
def frame(title):
print("=" * (len(title) + 4))
print(f"| {title} |")
print("=" * (len(title) + 4))
try:
yield len(title)
finally:
print("-" * (len(title) + 4))
with frame("hola") as length:
print("length:", length)
# ========
# | hola |
# ========
# length: 4
# --------
It is the structure of Decorative frame.
Why try/finally?
When the with block fails, the error is raised inside the generator, at the yield point. If the exit code is not in a finally, it does not run.
from contextlib import contextmanager
@contextmanager
def without_finally():
print("open")
yield
print("close") # does NOT run if there is an error
@contextmanager
def with_finally():
print("open")
try:
yield
finally:
print("close") # ALWAYS runs
for g in (without_finally, with_finally):
try:
with g():
raise ValueError("failure")
except ValueError:
print("error caught")
# open
# error caught
# open
# close
# error caught
Rule of thumb: always try/finally around the yield when there is something to release.
Catching the error inside the generator
If you put an except around the yield, you can handle the error inside the manager. If you catch it and do not raise it again, it is suppressed.
from contextlib import contextmanager
@contextmanager
def tolerant():
try:
yield
except KeyError as e:
print(f"missing key: {e}")
d = {"a": 1}
with tolerant():
print(d["b"])
print("goes on")
# missing key: 'b'
# goes on
Changing a value temporarily
A very common use: modify something, work, and restore the original value no matter what.
from contextlib import contextmanager
config = {"decimals": 2}
@contextmanager
def temporary(key, value):
previous = config[key]
config[key] = value
try:
yield
finally:
config[key] = previous
with temporary("decimals", 4):
print(config["decimals"]) # 4
print(config["decimals"]) # 2
try:
with temporary("decimals", 9):
raise RuntimeError("failure")
except RuntimeError:
print(config["decimals"]) # 2 (restored)
You apply it in Temporary setting.
Class or function?
| Use… | When… |
|---|---|
@contextmanager | the logic is short and linear: prepare, yield, clean up |
| a class | you need to keep state between uses, decide precisely according to the error, or reuse the manager many times |