function while true - list function?

Nick Perkins nperkins7 at home.com
Tue Jul 24 11:48:52 EDT 2001


"Giles Constant" <giles at spacepigs.com> wrote in message
news:88f77.300$e%3.6743 at news.lhr.globix.net...
> Hi there,
>
> is there a function in python which will populate a list with the results
> of a function while the function returns something other than 'None'?
I've
> looked for something but can't find much, but it's something I'm doing so
> often (especially while processing SQL databases) that I'm wondering if,
if
> it doesn't already exist, it could be a good idea for future versions.
>
> eg:
>
> def GrabSomeData:
>         somecursor.execute("SELECT x,y FROM z")
>         return unroll(somecursor.fetchone)   *
>
> * I figured "unroll" would be a good name for it :-)
>


Here's a version of unroll which can take extra args:

def unroll(fn,*args,**kwds):
    results = []
    x = fn(*args,**kwds)
    while x != None:
        results.append(x)
        x = fn(*args,**kwds)
    return results

for record in unroll(cursor.fetchone):
    process(record)

This will create a list of all results of your function,
up to, but not including the first 'None' result.

...
Here's another way to do it, using generators:
(in python 2.2)

from __future__ import generators
def gen_unroll(fn, *args, **kwds):
    x = fn(*args,**kwds)
    while x != None:
        yield x
        x = fn(*args,**kwds)

for record in gen_unroll(cursor.fetchone):
    process(record)
    if somecondition(): break

The difference, with the generator version, is that
results are not all computed and put in a list, as with the
first version of unroll; they are generated only as they are needed.

With the generator version, if you decide to break out of processing records
before all are done, you will have saved the time needed to fetch all
records in advance.






More information about the Python-list mailing list