Loading

Quipoin Menu

Learn • Practice • Grow

python / Context Managers
interview

Q1. What is a context manager in Python?
A context manager is an object that defines the runtime context to be established when executing a with block. It provides __enter__ and __exit__ methods for setup and cleanup. Common example: file handling with open().

Q2. How do you create a custom context manager?
Implement __enter__ and __exit__ methods in a class, or use the contextlib.contextmanager decorator with a generator. Example using class:
class MyContext: def __enter__(self): print("Entering") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Exiting")

Q3. What is the contextlib module?
contextlib provides utilities for working with context managers, including contextmanager decorator to turn generators into context managers, closing for objects with close(), and ExitStack for dynamic management.

Q4. How do you handle multiple resources with with?
You can use multiple context managers in a single with statement, separated by commas. Example:
with open(''input.txt'') as f1, open(''output.txt'', ''w'') as f2: data = f1.read() f2.write(data)

Q5. What is the purpose of the __exit__ method parameters?
__exit__ receives the exception type, value, and traceback if an exception occurred. If __exit__ returns True, the exception is suppressed; otherwise, it is propagated. This allows context managers to handle exceptions raised inside the with block.