Context Manager
PronunciationKON-tekst MAN-ij-er
Definition
A context manager sets something up when a with block starts and always cleans it up when the block ends, even if an error happens.
Where you hear it
In Python code that opens files, database connections or locks, and in explanations of the with statement.
Examples
with open(path) as f:closes the file automatically.We wrote a context manager that restores the setting after the test.
The lock is released by the context manager even when the handler raises an error.
Common mistake
Opening a resource without with and forgetting to close it when an error occurs.
Don't confuse with
A try / finally block, which does a similar cleanup by hand. A context manager packages it so it can be reused.
Say it at work
- In a meeting or chat
Wrap that in a
withblock so it always closes. - In an email or ticket
Make it a context manager so the cleanup can't be forgotten.
Keep exploring
More in Programming Fundamentals