You’ll be able to
- Use
withstatements to auto-manage resources - Understand what
__enter__and__exit__do - Write your own context managers with
contextlib - Guarantee cleanup even when errors occur
Loading lesson…
Why this matters
Every open(), requests.Session(), SQLAlchemy session.begin(), and threading.Lock is a context manager. Skipping with blocks is why production servers leak file handles and DB connections. contextlib.contextmanager and ExitStack are quiet superpowers.
Common pitfalls
- Opening files without
with— on CPython it works via refcount GC, but breaks on PyPy or under exceptions. - Forgetting to
yieldinside a@contextmanagerfunction — thewithblock silently getsNone. - Swallowing exceptions in
__exit__by returning truthy — only returnTruewhen you truly want to suppress.