The Enters and Exits of Context Managers
summary
Explains how Python guarantees teardown by implementing __enter__ and __exit__ in classes and using contextlib.contextmanager generators, shows a file-handle class that opens and closes explicitly, and demos two toy wrappers that uppercase or lowercase sys.stdout to prove setup/cleanup, including restoring original stdout. Covers passing parameters via __init__, how __exit__ receives (exc_type, exc_val, tb) and can suppress exceptions by returning True, and links to runnable examples on GitHub.
AI-written summary · about
chapters (11)
- 0:00Context managers intro
- 1:17Python context managers
- 2:39Common use cases
- 4:02Implementing as classes
- 6:10Enter method
- 7:55Exit method and exceptions
- 10:41Context managers with params
- 13:07Function-based managers
- 15:35Yield-based managers
- 16:56Exception handling in functions
- 17:58Summary
related talks
06mThe Enters and Exits of Context Managers
22mLearning Parseltongue: Wizardry in Python
01h 54mSo you want to be a Python expert?
31mGuardrails: An Alternative View of Safely Working in Python
26mA Beginners Guide to Context
23mDebugging that bugger : Cleanly handling the errors
18mDebugging Stories from an Advanced Python Class
23mThe Hitchhiker's Guide to CLIs in Python
