Book Image

Mastering Object-oriented Python

By : Steven F. Lott, Steven F. Lott
Book Image

Mastering Object-oriented Python

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (26 chapters)
Mastering Object-oriented Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Some Preliminaries
Index

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 line in line_iter)
        wtr.writerows( (m.groups() for m in match_iter if m is not None) )

Two contexts with two context managers were emphasized in this example.

The outermost context starts with with open("subset.csv",...