Managing contexts and the with statement

Contexts and context managers are used in several places in Python. We'll look at a few examples to establish the basic terminology.

A context is defined by the with statement. The following program is a small example that parses a logfile to create a useful CSV summary of that log. Since there are two open files, we expect to see nested with contexts. The example uses a complex regular expression, format_1_pat. We'll define this shortly.

We might see something like the following in an application program:

import gzip
import csv
with open("subset.csv", "w") as target:
    wtr= csv.writer( target )
    with gzip.open(path) as source: line_iter= (b.decode() for b in source) match_iter = (format_1_pat.match( line ) for ...

Get Mastering Object-oriented Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.