1. Technology
Send to a Friend via Email

Python 2.5's 'with' Statement


MacPython 2.5
urkonn/Flikr/CC BY 2.0
One of the new features that was released with Python 2.5 last month is the 'with' statement. For those of you who are used to Python's try...except statement, you may find this to be the biggest boon of upgrading. The basic structure is as follows:
 from __future__ import with_statement 
 with <expression> as <variable>: 
 Â Â Â Â with-block 
It is meant to replace the process so oft repeated:
 <setup your variables> 
 Â Â Â Â <action to be done> 
 Â Â Â Â <action to be done> 
 Â Â Â Â <action to be done> 
 Â Â Â Â <action to be done> 
One of the problems in this process is that, regardless of the actions to be done, the setup is always executed. This is less than optimum. If you have more than one type of the same kind of setup, things become verbose very quickly. If you have read my tutorial on inserting data into MySQL databases, you may recall the class Table. Python 2.5 now allows you to define a class and interact with it multiple times as follows:
 from __future__ import with_statement 
 class Table: 
 Â Â Â Â def __init__(self, db, name): 
 Â Â Â Â Â Â Â Â Â Â Â Â self.db = db 
 Â Â Â Â Â Â Â Â Â Â Â Â self.name = name 
 Â Â Â Â Â Â Â Â Â Â Â Â self.dbc = self.db.cursor() 
 Â Â Â Â def additem(self, item): 
 Â Â Â Â Â Â Â Â sql = "INSERT INTO " + self.name + " VALUES(" + id + ", " + item + ")" 
 Â Â Â Â Â Â Â Â self.dbc.execute(sql) 
 Â Â Â Â Â Â Â Â return 
 with Table as spreadsheet: 
 Â Â Â Â do something with spreadsheet variable 
Rather than define a Table instance separately, the setup becomes part and parcel of the code structure. Similarly, with file objects, one can skip the file object assignment line and simply put in the 'with' statement. In my ScripTip, I used the following basic structure:
 fileIN = open(sys.argv[1], "r") 
 line = fileIN.readline() 
 while line: 
 Â Â Â Â [some bit of analysis here] 
 Â Â Â Â line = fileIN.readline() 
Now in Python 2.5, I can simply write:
 from __future__ import with_statement 
 with open(sys.argv[1], "r") as fileIN: 
 Â Â Â Â for line in fileIN: 
 Â Â Â Â Â Â Â Â [some bit of analysis here] 
The new 'with' statement cuts the code needed from 5 to 3 and makes the program a bit more readable for humans. If you would like to read more about Python's 'with' statement, you can read about it at the main Python site or at Effbot.org.
  1. About.com
  2. Technology
  3. Python
  4. ScripTips
  5. Python 2.5's 'with' Statement - Python

©2014 About.com. All rights reserved.