Give a real example of where you have implemented a custom context manager. Explain how the __enter__ and __exit__ methods work.
💡 Model Answer
A common real‑world example is a context manager that handles a database connection. In the __enter__ method, the manager opens the connection and returns the connection object. In the __exit__ method, it checks for exceptions; if none, it commits the transaction, otherwise it rolls back, and finally it closes the connection. This guarantees that resources are cleaned up even if an error occurs. The pattern is useful for files, sockets, locks, or any resource that needs deterministic cleanup. The complexity of each operation is O(1), and the with‑statement ensures that __exit__ is always called, making the code safer and more readable.
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