Contexts and context managers

A context manager is used with the with statement. We work with a context manager when we write something like the following:

with function(arg) as context: 
    process(context) 

In the preceding code, function(arg) creates the context manager. Once the manager is available, the object can be used as needed. In the example, it's an argument to a function. A context manager class may have methods to perform actions within the scope of the context. 

One very commonly used context manager is a file. Any time a file is opened, a context should be used to guarantee that the file will also be properly closed. Consequently, we should almost always use a file in the following way:

with open("some file") as the_file: 
    process(the_file) 

At the end of the with statement, we're assured that the file will be closed properly. This will release any operating system resources, avoiding resource leaks or incomplete processing when exceptions are raised.

The contextlib module provides several tools for building proper context managers. Rather than providing an abstract base class, this library offers decorators, which will transform simple functions into context managers, as well as a contextlib.ContextDecorator base class, which can be extended to build a class that is a context manager.

We'll look at context managers in detail in Chapter 6, Using Callables and Contexts.

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

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