Q36: How does @contextlib.contextmanager simplify Context Manager generation?
The @contextlib.contextmanager decorator converts a generator function containing a single yield statement into a context manager. Code prior to yield acts as __enter__(); code after yield acts as __exit__().
Key Takeaways
- Converts generator functions into context managers.
- Pre-yield = setup (
__enter__); post-yield = cleanup (__exit__).
Knowledge Check
Where should cleanup code (file.close()) be placed inside a @contextlib.contextmanager function?