~/talk

The Enters and Exits of Context Managers

Talkat Conf42 Python 2021 · on Thursday, 2021-05-27· [python, software-architecture]
slides:none on file

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

  1. 0:00Context managers intro
  2. 1:17Python context managers
  3. 2:39Common use cases
  4. 4:02Implementing as classes
  5. 6:10Enter method
  6. 7:55Exit method and exceptions
  7. 10:41Context managers with params
  8. 13:07Function-based managers
  9. 15:35Yield-based managers
  10. 16:56Exception handling in functions
  11. 17:58Summary
~/search
type to search 6,249 conferences, 138,987 speakers and 185,172 talks
~/help
cmdctrl k
search every conference, speaker and series
/
focus the filter search
h
home
c
conferences
s
speakers
e
series
t
light / dark — the status bar button does the same
?
this help
esc
close this, then clear every filter — or just the search, while you are typing in it

Ignored while you are typing. Pages without a filter rail have no search to focus.