all Python 3contextlibterm
contextlib.contextmanager
decorator
Decorator that turns a generator function with a yield into a context manager.
Syntax
@contextlib.contextmanager
def my_cm(): ...; yield value; ...
If the with block raises, the exception is thrown back in at the yield point, so anything after yield is simply skipped. That is why cleanup almost always belongs in a try/finally around the yield — otherwise the resource leaks on errors. The object you get is single-use: the generator is exhausted after one with, so call the function again for a second block.
Examples
from contextlib import contextmanager
@contextmanager
def greet(name):
print('enter')
yield f'hi {name}'
print('exit')
with greet('Bob') as msg:
print(msg) # → enter / hi Bob / exit
# Очистка — в finally: выполнится и при исключении внутри with
import os, tempfile
from contextlib import contextmanager
@contextmanager
def tmp_file(name):
path = os.path.join(tempfile.gettempdir(), name)
open(path, 'w').close()
try:
yield path
finally:
os.remove(path)
with tmp_file('demo.txt') as p:
print(os.path.exists(p)) # → True
print(os.path.exists(p)) # → False
See also
Open in the full glossarydocs.python.orgReport an inaccuracy