Context Managers in Python — a practical guide to Python context managers with clear examples you can reuse in real projects.
Python Tutorial Series (55/95). Prefer one article? Read the complete Python tutorial.
Short description
Context managers guarantee cleanup. Files, locks, and DB sessions commonly use them.
custom context manager
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f'<{name}>')
yield
print(f'</{name}>')
with tag('div'):
print('content')