advancedAdvanced Topics

Context Managers

Manage resources safely with the with statement.

01The With Statement

Context managers handle setup and teardown of resources automatically.

Python
1# File context manager (built-in)
2with open("test.txt", "w") as f:
3 f.write("Hello!")
4# File is automatically closed here
5
6# Custom context manager with class
7class DatabaseConnection:
8 def __enter__(self):
9 print("Connecting to DB...")
10 return self
11
12 def __exit__(self, exc_type, exc_val, exc_tb):
13 print("Closing connection.")
14 return False
15
16with DatabaseConnection() as db:
17 print("Running queries...")
Output
Connecting to DB...
Running queries...
Closing connection.

02contextlib

Use contextlib for simpler context manager creation.

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