With statements got better with python 3.1

In my previous post about using the with statement in python /me had tried to throw some light on why to use 'with' statements and the fun of using them.

Had also mentioned about, the contextlib module for python 2.7+ but with 3.X 'with statements' were better and the fun multiplied!

Let's see a small example on why 'with' has become better with python 3.1

>>> with open('site.log') as infile, open('err.log', 'w') as outfile:
...     for line in infile:
...         if 'ERROR' in line:
...             outfile.write(line)

Mind == BLOWN

It's so easy to handle multiple files with 'with statements' in python 3.1! Not that it's only in this version, but 3.X series has a better potential, is what is been alluded here.

Basically the only difference is that Python's with operates over a context management protocol involving some __magic__ methods so it can work with other things in addition to files.

Update 0 : 2.7 supports multiple context managers too! Despite the numbering, 2.7 was released a year after 3.1. It added a bunch of features that helped compatibility with 3.x.

Share this