Context Managers
summary
It's the 20th anniversary of PEP 343 and the talk shows why context managers prevent "too many open files" bugs (garbage collection can hide the problem but with blocks files reliably close), demonstrates using contextlib.contextmanager (generator + yield with try/finally) to build enter/exit logic, lists real uses — redirecting stdout, lock/transaction handling, timing, Trio nurseries — and explains making global-like state async-safe with contextvars (log-prefix example uses set/reset and works under concurrent tasks).
AI-written summary · about
chapters (12)
- 0:00Introduction and setup
- 1:31Context managers in 2025
- 3:57Why context managers matter
- 6:01How context managers work
- 9:38Understanding the protocol
- 10:20Practical examples
- 12:05Functions twice as cool
- 15:37Creating context managers
- 17:28Scope and naming confusion
- 20:29Global state and context vars
- 24:02Context vars in depth
- 24:46Conclusion and Q&A
