Context Managers (with)
Python · Intermediate
Definition
A context manager sets up and tears down a resource automatically using the with statement.
Guarantees files, locks and connections are closed even on errors.
Diagram
Flowchart
Example: Custom context manager
from contextlib import contextmanager
@contextmanager
def tag(n):
print(f'<{n}>'); yield; print(f'</{n}>')
with tag('b'):
print('hi')Output: <b> hi </b>
Key points
- Always open files with with
- contextlib simplifies writing them
Interview questions
Does __exit__ run on exceptions?
Yes, and it can choose to suppress the exception.