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>
try:
    <action to be done>
except:
    <action to be done>
else:
    <action to be done>
finally:
    <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.