variable assignment in "while" loop

Raymond Hettinger vze4rx4y at verizon.net
Wed Jul 30 10:25:40 CEST 2003


> >>Spot on, with one (minor) correction. With a for loop you have to
> >>iterate over the results of a call to a method on the cursor, e.g.;
> >>
> >>for info in mydbcursor.fetchall():
> >>     print "Information:", info
> >>
> >>You could replace fetchall() with fetchmany() or, if you are feeling
> >>contrary, fetchone() ;-)
> >
> >
> > Are you sure about this?  Because, if you have to iterate
> > through .fetchall()  (for example), then the cursor isn't
> > actually an iterable object, the result of fetchall() is
> > (it's a list, which is iterable), same goes for fetchmany();
> > BUT, if you iterate over the results of fetchone() then
> > you're gonna do a columnwise iteration over a single row.
> >
> > So... anyone... do cursors have an __iter__() method?
> > I don't have a DB module at hand to check it out...
>
> Technically, cursor objects are not iterators, and the DB-API
> specification has this to say about the various methods that return data;
>
> """
> .fetchone()
>
> Fetch the next row of a query result set, returning a
> single sequence, or None when no more data is
> available.

Remember, the second form of the iter() function makes
it easy to build a real iterator here and a fast one too:

    for row in iter(mydbcursor.fetchone, None):
          print row



> .fetchall()
>
> Fetch all (remaining) rows of a query result, returning
> them as a sequence of sequences (e.g. a list of tuples).
> """
>
> Which means that the cursor object itself is not an iterator, and the
> methods need only return a sequence (or sequence of sequences).


Right, so if you want iterator performance (just-in-time production,
minimal memory consumption, better cache utilization, etc), then use
fetchone wrapped in iter() as shown above.


Raymond Hettinger






More information about the Python-list mailing list