Other contexts
There are a few other common contexts. Almost all of them are associated with basic input/output operations. Most modules that open a file create a context along with the file-like object.
Contexts are also associated with locking and database transactions. We may acquire and release an external lock, such as a semaphore, or we may want a database transaction to properly commit when it's successful or roll back when it fails. These are all the things that have defined contexts in Python.
The PEP 343 document provides a number of other examples of how the with statement and context managers might be used. There are also other places where we might like to use a context manager.
We may need to create classes that are simply context ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access