Two Ways to Define a Context Manager in Python 2026
Context managers are one of Python’s most elegant features for resource management. In 2026, there are two primary ways to create them: using a class with `__enter__` and `__exit__`, or using the `@contextmanager` decorator. Understanding both approaches is essential for writing clean and robust functions.
TL;DR — Key Takeaways 2026
- Class-based context managers offer more control and are better for complex state
- The `@contextmanager` decorator is simpler and more readable for most cases
- Use `ExitStack` when you need to manage a dynamic number of resources
- Always ensure proper cleanup even when exceptions occur
1. Class-Based Context Manager
class DatabaseConnection:
def __init__(self, db_url: str):
self.db_url = db_url
self.connection = None
def __enter__(self):
self.connection = connect_to_database(self.db_url)
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
if self.connection:
self.connection.close()
# Return False to let exceptions propagate
# Usage
with DatabaseConnection("postgresql://...") as conn:
result = conn.query("SELECT * FROM users")
2. Decorator-Based Context Manager (@contextmanager)
from contextlib import contextmanager
@contextmanager
def timer(name: str):
"""Simple timer context manager."""
import time
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f"{name} took {elapsed:.4f} seconds")
# Usage
with timer("Database query"):
result = run_expensive_query()
3. When to Use Which Approach
- Use `@contextmanager` for simple, short-lived resource management
- Use class-based when you need complex state, multiple methods, or reusable objects
- Use `ExitStack` when the number of context managers is dynamic
Conclusion
Both class-based and decorator-based context managers have their place in modern Python development. In 2026, choosing the right approach helps you write cleaner, safer, and more maintainable code when working with resources.
Next steps:
- Review your resource management code and refactor using the most appropriate context manager pattern
- Related articles: Using Context Managers in Python 2026 • Nested Context Managers in Python 2026