Nested Context Managers in Python 2026 – Best Practices for Writing Functions
Managing multiple resources (files, database connections, locks, etc.) simultaneously is common in real-world functions. In 2026, using nested context managers correctly is essential for writing safe, clean, and resource-efficient code.
TL;DR — Key Takeaways 2026
- Use multiple
withstatements to manage several resources safely - Prefer
contextlib.ExitStackfor dynamic numbers of context managers - Nested context managers ensure proper cleanup even if exceptions occur
- Always handle resources in the correct order (LIFO)
1. Basic Nested Context Managers
# Simple nested with statements
with open("input.txt", "r") as infile:
with open("output.txt", "w") as outfile:
for line in infile:
outfile.write(line.upper())
2. Cleaner Nested Contexts with ExitStack (Recommended)
from contextlib import ExitStack
def process_multiple_files(file_paths):
with ExitStack() as stack:
files = [stack.enter_context(open(path, "r")) for path in file_paths]
# Now safely work with all files
for f in files:
content = f.read()
# process content...
3. Real-World Example with Database and File
from contextlib import ExitStack
async def export_user_data(user_id: int, output_path: str):
with ExitStack() as stack:
# Open database session
db_session = stack.enter_context(get_db_session())
# Open output file
output_file = stack.enter_context(open(output_path, "w"))
# Both resources are safely managed
user_data = await db_session.get_user(user_id)
output_file.write(str(user_data))
# Both will be closed automatically, even if an exception occurs
4. Best Practices for Nested Contexts in 2026
- Use
ExitStackwhen the number of context managers is dynamic - Keep nesting shallow — extract complex logic into separate functions
- Always use context managers for resources that need cleanup
- Order matters: resources are cleaned up in reverse order of acquisition
- Combine with
async withfor asynchronous context managers
Conclusion
Nested context managers are a powerful tool for managing multiple resources safely. In 2026, using ExitStack and proper nesting patterns is considered best practice for writing robust, exception-safe functions that handle resources correctly.
Next steps:
- Review your functions that manage multiple resources and refactor them using
ExitStack - Related articles: Using Context Managers in Python 2026 • Writing Functions in Python 2026