[Fwd: while row = c.fetchone(): # syntax error???]

Alex Martelli alex at magenta.com
Fri Aug 11 08:39:12 EDT 2000


"Just van Rossum" <just at letterror.com> wrote in message
news:3993EC14.E68C5618 at letterror.com...
    [snip]
> >
> > > into the equivalent Python idiom:
> > >
> > >     while 1:
> > >         row=c.fetchone()
> > >         if not row: break
> > >         doit(row)
    [snip]
> And now for the "official" Python idiom, which avoids duplication of the
> t = c.fetchone() line:
>
> while 1:
>     t = c.fetchone()
>     if not t:
>         break
>     --- # Very intelligent code goes here :)

Where the difference with the idiom I proposed, above-quoted, is the
linebreak after the "if not t:" ("if not row:" in my version), I guess.
Well,
I'm not impressed; this is one case where I don't want to emphasize
Python's weakness, having already had to expand the one-line idiom
    while row=c.fetchone():
into three -- making them four rather than 3 is no progress!-)

I do agree that duplicating the call to c.fetchone in two places is the
worst solution (because you'll have to edit two places to keep them
the same, anytime that changes).  But I don't even particularly like
the standard 3-liner I've proposed.  I've already mentioned one
class-based alternative, but another is:

    for row in iterator(c.fetchone):
        doit(row)

with, obviously, hidden somewhere in a myutil.py...:

class iterator:
    def __init__(self,iter):
        self.iter=(iter,)
    def __getitem__(self,index):
        nextone=self.iter[0]()
        if not nextone:
            raise IndexError
        return nextone

plus error-checking if one wants, of course:-).


Alex






More information about the Python-list mailing list