September 2026
1051 pages
35h 4m
English
There are operations that must be executed in a certain context and for which it must be ensured that the context is correctly deinitialized at all times—for example, even if an exception occurs. An example of such a context is an open file object: You must ensure that the close method of the file object is called even if an exception was raised between the call of open and that of the close method of the file object.
For these purposes, Python defines context objects. These are objects that have the magic __enter__ and __exit__ members to enter and exit the context, respectively. For the use of context objects, there is the with statement, which you’ll get to know in the following section.
If you ...
Read now
Unlock full access