pythonintermediate
Custom Context Manager with __enter__ / __exit__
Build reusable resource management with Python context managers.
pythonPress ⌘/Ctrl + Shift + C to copy
import time
from contextlib import contextmanager
# Class-based context manager
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.elapsed = time.perf_counter() - self.start
print(f"Elapsed: {self.elapsed:.4f}s")
return False # Don't suppress exceptions
with Timer() as t:
sum(range(1_000_000))
# Generator-based (simpler)
@contextmanager
def temp_directory():
import tempfile, shutil
path = tempfile.mkdtemp()
try:
yield path
finally:
shutil.rmtree(path)
with temp_directory() as tmpdir:
print(f"Working in {tmpdir}")Use Cases
- Resource cleanup
- Timing code
- Temporary directories
- Database connections
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
#context-manager#resource-management
pythonintermediate
Python Context Manager Patterns
Create custom context managers with __enter__/__exit__ and contextlib for resource management.
Best for: Automatic resource cleanup and lifecycle management
#python#context-manager
pythonintermediate
contextlib Utilities for Resource Management
Use contextlib for lightweight context managers, suppressing exceptions, and redirect output.
Best for: timing code
#python#contextlib
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation