Can you explain how context managers work in Python?
💡 Model Answer
A context manager in Python is an object that defines the methods __enter__ and __exit__. When you use the with statement, Python calls __enter__ at the start of the block and passes its return value to the variable after the as keyword. When the block exits—whether normally or due to an exception—Python calls __exit__, passing exception details if any. This mechanism ensures that resources such as files, locks, or network connections are properly acquired and released. The built‑in open() function, for example, returns a file object that is a context manager. The contextlib module also provides decorators to turn simple functions into context managers.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500