Python / Core Python Fundamentals Interview Questions
What is a context manager in Python and how do you implement one?
A context manager controls setup and teardown around a block of code via the with statement. The canonical example is file handling, but context managers are used for database transactions, locking, temporary directory creation, patching in tests, and any resource that needs guaranteed cleanup.
Python calls __enter__ when entering the with block and __exit__ when leaving it — even if an exception is raised. The value returned by __enter__ is bound to the as variable.
class Timer: import time def __enter__(self): self._start = self.time.perf_counter() return self # bound to 'as t' def __exit__(self, exc_type, exc_val, exc_tb): self.elapsed = self.time.perf_counter() - self._start print(f'Elapsed: {self.elapsed:.4f}s') return False # False = do not suppress exceptions with Timer() as t: result = sum(range(1_000_000)) print(t.elapsed)
The simpler way for most cases is contextlib.contextmanager, which turns a generator function into a context manager — everything before yield is setup, everything after is teardown:
from contextlib import contextmanager @contextmanager def managed_connection(dsn): conn = connect(dsn) try: yield conn # the value of 'conn' in 'with ... as conn' finally: conn.close() # runs even if an exception occurred
More Related questions...