Context manager design considerations and trade-offs

A context is generally used for acquire/release, open/close, and lock/unlock types of operation pairs. Most of the examples are file I/O related, and most of the file-like objects in Python are already proper context managers.

A context manager is almost always required for anything that has steps that bracket the essential processing. In particular, anything that requires a final close() method should be wrapped by a context manager.

Some Python libraries have open/close operations, but the objects aren't proper contexts. The shelve module, for example, doesn't create a proper context.

We can (and should) use the contextllib.closing() context on a shelve file. We'll show this in Chapter 10, Serializing and Saving – JSON, YAML, Pickle, CSV, and XML.

For our own classes that require a close() method, we can use the closing() function. When confronted with a class that has any kind of acquire/release life cycle, we want to acquire resources in __init__() or a class-level open() method and release them in close(). That way, our class can integrate well with this closing() function.

The following is an example of a class being wrapped that requires a close() function:

with contextlib.closing(MyClass()) as my_object: 
    process(my_object) 

The contextllib.closing() function will invoke the close() method of the object that is given as an argument. We can guarantee that my_object will have its close() method evaluated.

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

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