Python Context Managers
Manage resources properly using context managers.
Handle resources safely.
With Statement
```python # File auto-closes with open("data.txt", "r") as file: content = file.read() print(content) # File is closed here automatically ```
Create Context Manager
```python class DatabaseConnection: def __enter__(self): print("Opening connection...") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Closing connection...") def query(self, sql): print(f"Running: {sql}")
with DatabaseConnection() as db: db.query("SELECT * FROM users") # Opening connection... # Running: SELECT * FROM users # Closing connection... ```
Using contextlib
```python from contextlib import contextmanager
@contextmanager def timer(): import time start = time.time() yield end = time.time() print(f"Time: {end - start:.4f}s")
with timer(): sum([i for i in range(1000000)]) # Time: 0.0453s ```
Multiple Context Managers
```python with open("input.txt") as infile, \ open("output.txt", "w") as outfile: content = infile.read() outfile.write(content.upper()) ```
Remember
- Always use with for files - Ensures cleanup happens - Create custom for resources