Context Manager in Python — Python Technical Interview Questions & Answers

Context Manager in Python

Context Manager in Python

  • A context manager sets up and cleans up automatically. with expression as var: guarantees cleanup on the way out — even if an error fires. Files: with open(path) as f:. You can write your own with __enter__ / __exit__ or contextlib. Mental model: acquire, use, release. with is safer than open + close that you might forget.
  • Why with beats manual close(): an exception in the middle still closes the file. That sentence is the viva.
  • Context Manager in Python — output: Hi. with guarantees close — same idea as with open("a.txt").

Technical Interview Tip: Why with is safer than manual close().

Code Examples for Context Manager in Python

Example

# Context manager
from contextlib import closing
from io import StringIO
with closing(StringIO("Hi")) as f:
    print(f.read())

Context Manager in Python — output: Hi. with guarantees close — same idea as with open("a.txt").

How to Explain Context Manager in Python to an Interviewer

Explain Context Manager as if you are teaching a junior — definition, then one tiny script.

with = setup + cleanup. File example first.

What does the example print, and why?

Context Manager in Python — output: Hi

What mistake do freshers make with Context Manager?

__enter__ / __exit__.