7.11 Creating contexts and context managers
A number of Python objects behave like context managers. Some of the most visible examples are file objects. We generally use with path.open() as file: to process a file in a context that can guarantee the resources are released. In Chapter 2, the Managing a context using the with statement recipe covers the basics of using a file-based context manager.
How can we create our own classes that act as context managers?
7.11.1 Getting ready
We’ll look at a function from Chapter 3, in the Picking an order for parameters based on partial functions recipe. This recipe introduced a function, haversine(), which has a context-like parameter used to adjust the answer from dimensionless radians to a useful unit of measure, such as kilometers, nautical miles, or US statute miles. In many ways, this distance factor is a kind of context, used to define the kinds of computations...