Python Developer interview question
How do Python context managers work?
A context manager brackets resource acquisition and cleanup through __enter__ and __exit__, guaranteeing cleanup on normal completion or exception; with is the standard way to use it.
Direct answer
What a strong answer covers
How it works
The with statement calls __enter__ on entry, binds its return value to the target, and guarantees __exit__ runs on the way out, whether by normal completion, return, or exception. __exit__ receives the exception details and can suppress the error by returning True, which is rarely wanted. contextlib.contextmanager turns a generator with one yield into a context manager, and ExitStack composes a variable number of them. The pattern applies to anything with setup and teardown, not only files and locks.
Example
A database session wrapper opens a transaction in __enter__, commits in __exit__ when no exception occurred, and rolls back otherwise, so business code stays free of try and finally. A test helper written with contextmanager temporarily overrides an environment variable and restores it even when the assertion fails.
Common mistakes
- Returning True from __exit__ by accident and silently swallowing every exception.
- Acquiring a resource in __init__ instead of __enter__, so the resource exists before the with block.
- Nesting many with statements manually when ExitStack would keep the code flat.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.