Skip to Content
Mastering Object-oriented Python
book

Mastering Object-oriented Python

by Steven F. Lott
April 2014
Beginner to intermediate
634 pages
15h 22m
English
Packt Publishing
Content preview from Mastering Object-oriented Python

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Object-Oriented Python - Second Edition

Mastering Object-Oriented Python - Second Edition

Steven F. Lott

Publisher Resources

ISBN: 9781783280971Supplemental Content