Describing Context Management
- A context manager refers to any object that can be executed using the
withstatement - The general syntax is as follows:
with context [as var]:
statements__enter__()is invoked when thewithstatement executes- The value returned by this method is placed into the variable specified as
[as var] - It is then passed through to the remainder of the
withblock __exit__()is invoked at the end of awithstatement- Primarily, the context management interface allows for simplified field resource control on objects involving system state
- By implementing this interface, objects can safely clean up resources when execution leaves a context
-
Examples of objects involving system state are:
- Open files
- Network connections
- Locks
Summarizing Special Methods
| Method | Description |
|---|---|
__enter__ |
Called when entering a new context |
__exit__ |
Called when leaving a context |
References
Previous
Next