Exception Handling
Context Managers
Resource management with the with statement
Interview: Pythonic resource handling — tests understanding of __enter__/__exit__, contextlib, and resource safety
Context managers ensure that resources are properly acquired and released, even when exceptions occur. The with statement is the most Pythonic way to manage files, connections, locks, and any resource that needs cleanup. They're implemented via the __enter__/__exit__ protocol or the contextlib module.
How Context Managers Work
__enter__(): Called when entering the with block (setup)__exit__(exc_type, exc_val, exc_tb): Called when leaving (cleanup)- If
__exit__returnsTrue, exceptions are suppressed - If
__exit__returnsFalseorNone, exceptions propagate
contextlib Module
@contextmanager: Create context managers from generator functionsExitStack: Manage multiple context managers dynamicallysuppress(): Ignore specific exceptions
Interview Tip
Know the difference between class-based and generator-based context managers. Also understand when __exit__ should return True (suppress exception) vs False (propagate).
Use Cases
File handling: automatic close even on exceptions
Database transactions: commit on success, rollback on failure
Lock management: acquire/release thread/process locks
Temporary resources: files, directories, network connections
Timing/profiling: measure execution time of code blocks
Common Mistakes
Forgetting to yield in @contextmanager generator (must yield exactly once)
Not handling exceptions in __exit__ (cleanup must work even on errors)
Returning True from __exit__ accidentally (suppresses exceptions silently)
Using context managers when simple try/finally would be clearer
Not understanding that the value after