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 managers, or we may need to create classes that can have multiple purposes, one of which is to be a context manager. We'll look at a number of design strategies for contexts.

We'll return to this again in Chapter 9, Decorators and Mixins – Cross-Cutting Aspects, where we can cover a few more ways to create classes that have context manager features.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset