
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, like 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 other places where we might like to use a context manager.
We may need to create classes that are simply context managers, or we may need to create classes that can have multiple purposes, one of which is to be a context manager. The file()
object is similar. We'll look at a number of design strategies for contexts.
We'll return to this again in Chapter 8, Decorators and Mixins – Cross-cutting Aspects, where we can cover a few more ways to create classes that have context manager features.