What is Python's context managers and the contextlib module?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
The contextlib module provides utilities for creating and working with context managers. @contextmanager: creates a context manager from a generator function using yield — code before yield runs in __enter__, code after in __exit__: @contextmanager def managed_resource(): resource = acquire(); try: yield resource; finally: release(resource). contextlib.suppress(*exceptions): suppress specific exceptions: with suppress(FileNotFoundError): os.remove("file.txt"). contextlib.redirect_stdout(f): redirect stdout to a file object. contextlib.ExitStack: manage multiple context managers dynamically — enter variable numbers of CMs at runtime. contextlib.asynccontextmanager: async version of contextmanager. AbstractContextManager: base class for creating CM classes. Context managers are the Pythonic way to handle resource acquisition and release.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Python codebase.
Previous
What is Python's virtual environment and dependency management?
Next
What is Python's metaclasses?