Category: python
Class-based Context Manager
Published on 27 Oct 2026
Explanation
Implement __enter__ for setup and __exit__ for cleanup when a class manages a resource or state.
Code:
class Session:
def __enter__(self): print('Open'); return self
def __exit__(self, exc_type, exc_value, traceback): print('Close'); return False
with Session(): print('Work')
Explanation
contextlib.contextmanager lets a generator define setup before yield and cleanup in finally.
Code:
from contextlib import contextmanager
@contextmanager
def resource():
print('Setup')
try: yield 'Ready'
finally: print('Cleanup')
with resource() as value: print(value)
Explanation
A generator context manager can catch exceptions from the managed block at yield. Re-raise unless intentionally handling them.
Code:
from contextlib import contextmanager
@contextmanager
def transaction():
print('Begin')
try: yield
except Exception:
print('Rollback')
raise
else: print('Commit')
with transaction(): print('Work')
Explanation
A context manager can temporarily change a setting and restore the prior state in finally.
Code:
from contextlib import contextmanager
settings = {'debug': False}
@contextmanager
def temporary():
old = settings['debug']; settings['debug'] = True
try: yield
finally: settings['debug'] = old
with temporary(): print(settings['debug'])
print(settings['debug'])
Explanation
A context manager can measure a block's elapsed time with time.perf_counter().
Code:
from contextlib import contextmanager
from time import perf_counter
@contextmanager
def timer():
start = perf_counter()
try: yield
finally: print(perf_counter() - start)
with timer(): sum(range(100_000))