while (assignment):

Bengt Richter bokr at oz.net
Wed Jul 30 11:18:00 EDT 2003


On 30 Jul 2003 05:19:07 -0700, mis6 at pitt.edu (Michele Simionato) wrote:

>Sybren Stuvel <sybrenUSE at YOURthirdtower.imagination.com> wrote in message news:<slrnbieppo.86l.sybrenUSE at sybren.thirdtower.com>...
>> Hannu Kankaanpää enlightened us with:
>> > Typically this is done by breaking out of the loop:
>> > 
>> > while True:
>> >     info = mydbcursor.fetchone()
>> >     if not info:
>> >         break
>> >     print "Information: "+str(info)
>> 
>> This was my first solution as well. Kinda ugly, though.
>> 
>> Sybren
>
>When I started using Python I though the "while 1" idiom was horrible.
>Now I think it is quite Pythonic. Few months can change your mind! ;)
>
>You may also use this form, which you may find more readable:
>
>while 'info': 
>     info = mydbcursor.fetchone()
>     if not info: break
>     print "Information: "+str(info)
>
>Remember, 'info' is another spelling of True!
>This is a trick anyway, and I always use "while 1" in my code, it is
>the idiomatic way at the end.
>
>                        Michele

Using a one-line class definition and instantiation (and silly aliasing)

 >>> keeping = info = type('',(),{'__call__':lambda o,*a:a and setattr(o,'v',a[0]) or o.v})()
 >>> fun = iter((1,5,0,9)).next
 >>> while keeping(fun()): print info()
 ...
 1
 5


which would let you spell it

    while keeping(mydbcursor.fetchone()):
        print "Information: %s" % info()

;-)

Regards,
Bengt Richter




More information about the Python-list mailing list