Protocols & Type Systemhigh

Context Managers

Objects that implement __enter__ and __exit__ to guarantee setup/teardown around a with block, even if an exception occurs.

Memory anchor

Context manager = a responsible babysitter. __enter__ = babysitter arrives, __exit__ = babysitter cleans up toys before leaving, NO MATTER WHAT happened (even if the kid threw a tantrum/exception).

Expected depth

with open('f') as f: calls f.__enter__() at entry and f.__exit__() at exit (even on exception). __exit__(exc_type, exc_val, exc_tb) receives exception info — return True suppresses the exception. contextlib.contextmanager turns a generator function into a context manager: yield = the with body runs here. contextlib.suppress(ExceptionType) suppresses specific exceptions.

Deep — senior internals

contextlib.contextmanager is the most practical way to write context managers without a full class. The generator must have exactly one yield. Try/finally in the generator ensures cleanup: try: yield finally: cleanup(). contextlib.ExitStack manages a dynamic number of context managers (useful when you don't know at code-writing time how many resources to open). __exit__ returning a truthy value suppresses the exception — this is a feature, not a bug, used by contextlib.suppress. Async context managers use __aenter__/__aexit__ and async with.

🎤Interview-ready answer

Context managers guarantee cleanup via __enter__/__exit__, even on exceptions. with statements call __exit__ regardless of how the block exits. I use contextlib.contextmanager to write them as generators — much cleaner than a full class. The pattern is: setup, yield, cleanup in a try/finally. Common uses: database transactions (commit or rollback), file locks, temporary directories, mocking in tests. __exit__ can suppress exceptions by returning True.

Common trap

contextlib.contextmanager functions must have exactly one yield. If an exception occurs in the with body, it's re-raised at the yield point — handle it with try/except around the yield if you want to react to it.

Related concepts