Using Context Managers in Python 2026 – Best Practices for Writing Functions
Context managers are one of Python’s most elegant and powerful features. They ensure resources are properly acquired and released, making your code safer, cleaner, and more reliable. In 2026, mastering context managers is considered essential for writing professional-grade functions.
TL;DR — Key Takeaways 2026
- Use the
withstatement to manage resources automatically - Create custom context managers with the
contextlibmodule - Always use context managers for files, database connections, locks, etc.
- They help prevent resource leaks and make code more readable
1. Basic Usage
# Traditional way (error-prone)
file = open("data.txt", "r")
try:
content = file.read()
finally:
file.close()
# Modern, clean way with context manager
with open("data.txt", "r") as file:
content = file.read()
# File is automatically closed here
2. Creating Custom Context Managers
from contextlib import contextmanager
@contextmanager
def timer(name: str):
"""Context manager to time code blocks."""
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()
# Class-based context manager
class DatabaseConnection:
def __enter__(self):
self.conn = connect_to_db()
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()
3. Best Practices in 2026
- Use context managers for **all** resources that need cleanup (files, sockets, locks, database connections)
- Prefer the
@contextmanagerdecorator for simple cases - Use class-based context managers when you need more complex state management
- Always handle exceptions properly in
__exit__ - Combine multiple context managers using
contextlib.ExitStack
Conclusion
Context managers are one of Python’s greatest features for writing safe and clean code. In 2026, using the with statement and creating custom context managers should be your default approach whenever you work with resources that need proper setup and teardown.
Next steps:
- Review your functions and replace manual resource management with context managers
- Related articles: Writing Functions in Python 2026 • Efficient Python Code 2026