Intermediate·7 min·intermediate · resources
Context Managers (`with`)
Context Managers (with)
with thing as x: guarantees that setup runs first and cleanup runs after — even if the block raises.
Classic uses
- File I/O:
with open(path) as f: - Locks, DB transactions, temporary directories
- Timing, profiling, logging blocks
Build your own
@contextmanager on a generator function: code before yield is enter, code after yield is exit.
Try it
- Write a
silenced()context manager that swallows specific exceptions in its block. - Use
timingto comparesum(range(N))vs a manualfor-loop sum.