nice Python Generators example
Todd links to a good example of generators in Python. You can do things like this in many languages with varying degrees of ease. In C you probably need to explicitly store all your state; in Scheme you probably need to explicitly get your head around continuations. Python is arguably the first mainstream language to add them as a first-class feature. It will be interesting to see how much people pick them up and use them. They're probably not something you want to use very often, but when you want them they're very handy.
The "level of elegance" in providing explicit generators is very typical of Python: you certainly could factor them into smaller components and write the rest as a library, but it's perhaps easier to use them in this packaging.
def genResults(db, sql):
cursor=db.cursor()
cursor.execute(sql)
while 1:
row=cursor.fetchone()
if row is None: break
yield row
posted Wed 18 Jun 2003 in /software/languages/python | link
Archives 2008: Apr Feb 2007: Jul May Feb Jan 2006: Dec Nov Oct Sep Aug Jul Jun Jan 2005: Sep Aug Jul Jun May Apr Mar Feb Jan 2004: Dec Nov Oct Sep Aug Jul Jun May Apr Mar Feb Jan 2003: Dec Nov Oct Sep Aug Jul Jun May
Copyright (C) 1999-2007 Martin Pool.