What are Context Managers?
In Python, a context manager is an object that handles the setup and teardown logic for a resource automatically. The most common use case is opening a file. Using a context manager ensures that the resource (like a file or database connection) is closed correctly, even if an error occurs.
python
How It Works: The __enter__ and __exit__ Methods
Any class can become a context manager by implementing these two magic methods.
__enter__: Setup logic. Runs at the start of thewithblock.__exit__: Teardown logic. Runs at the end of thewithblock (and handles any exceptions!).
python
Using contextlib: The Shortcut!
Writing a class for every context manager can be overkill. The
contextlib module provides a decorator that turns a generator function into a context manager using yield.python
Summary
| Feature | Method / Syntax |
|---|---|
| with | The keyword to activate a context manager |
| enter | Setup logic |
| exit | Cleanup/Teardown logic |
| yield | Used in contextlib to separate setup and teardown |
| Best For | File I/O, DB Connections, Locks, Timers |
| Safety | Ensures resources are cleaned up even on crash |