Courses/Modern Python

๐Ÿš€ Modern Python

Custom Context Managers

The 'with' statement, your way.

Any object with __enter__ and __exit__ works with with. Or use @contextmanager for the easy path.

from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"<{name}>")
    yield
    print(f"</{name}>")

with tag("h1"):
    print("Hello")
main.py
Output
Press Run to execute.
Expected output
=== Report ===
line 1
=== end ===

Sign in to track your progress across lessons.