June 2019
Beginner to intermediate
770 pages
19h 24m
English
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 ...
Read now
Unlock full access