L4·OOP & Errors

🚪Context Managers (with)

Guaranteed setup and teardown.

withcontext__enter____exit__

§ 1The protocol

__enter__(self) runs at the start of with. __exit__(self, exc_type, exc, tb) runs at the end, even on exception.

§ 2contextlib.contextmanager

Turn a generator with a single yield into a context manager.

Example

1from contextlib import contextmanager​
2​
3@contextmanager​
4def tag(name):​
5 print(f"<{name}>")​
6 yield​
7 print(f"</{name}>")​
8​
9with tag("h1"):​
10 print("Hello")​

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
What guarantees a file is closed?