with (context managers)
`with` sets something up when a block starts and cleans it up when the block ends, even if an error happens.
Used in 35 lessons of the course, from 01.02.
A context manager is an object that knows what to do when a block starts and what to do when it ends. with uses that object.
The shape is with obj as name:. On entry, Python calls __enter__; the value it returns lands in name. When the block ends, Python calls __exit__, no matter what: normal end, return, or an exception.
That's why it's written this way: the cleanup doesn't depend on you remembering it. It works like a try/finally, but shorter and harder to forget.
The as name part is optional. If only the enter and exit effects matter, leave it out.
In the course you see it in lesson 01.02: with warnings.catch_warnings():. Inside the block, warnings are handled in a special way, and on exit everything goes back as it was.
with open_thing() as t:
use(t)
Reach for it when: something must be closed, released or restored after you use it, like a file, a lock or a temporary setting.
Examples
Common mistake
with 42 as n:
print(n)Why: `with` needs an object that has `__enter__` and `__exit__`. An integer has neither.
How to write it: Use a real context manager, such as open(...) or warnings.catch_warnings().
Common mistake
class Demo:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return True
with Demo():
raise ValueError("boom")
print("continues")Why: If `__exit__` returns a true value, the exception is swallowed and the error vanishes silently.
How to write it: Return False or None from __exit__ unless you mean to hide the error.
