Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Mastering Object-oriented Python
  • Toc
  • feedback
Mastering Object-oriented Python

Mastering Object-oriented Python

By : Steven F. Lott
4.2 (13)
close
Mastering Object-oriented Python

Mastering Object-oriented Python

4.2 (13)
By: Steven F. Lott

Overview of this book

Table of Contents (26 chapters)
close
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",...

Unlock full access

Continue reading for free

A Packt free trial gives you instant online access to our library of over 7000 practical eBooks and videos, constantly updated with the latest in tech
bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete