What problem do context managers solve?medium
Answer
Context managers guarantee setup and cleanup around a block of code, even when exceptions occur. __enter__ prepares the resource and __exit__ releases it.
Explanation
Context managers power patterns like with open(...) because the file handle is always closed even if an exception is raised inside the block. You can implement them either by defining __enter__ and __exit__ on a class, or more simply with @contextlib.contextmanager and a yield. Returning True from __exit__ suppresses the exception. Generator-based dependencies in FastAPI (yield in Depends) follow the same pattern for guaranteed teardown.
Follow-upHow would you create a custom context manager?
Follow-upWhat does __exit__'s return value control?