advancedAdvanced Topics
Context Managers
Manage resources safely with the with statement.
In this lesson
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 here56# Custom context manager with class7class DatabaseConnection:8 def __enter__(self):9 print("Connecting to DB...")10 return self1112 def __exit__(self, exc_type, exc_val, exc_tb):13 print("Closing connection.")14 return False1516with 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 contextmanager23@contextmanager4def tag(name):5 print(f"<{name}>")6 yield7 print(f"</{name}>")89with tag("div"):10 print(" Hello, World!")
Output
<div> Hello, World! </div>