while (a=b()) ...

Andrew Dalke dalke at bioreason.com
Thu Apr 29 20:26:56 EDT 1999


Marco Mariani <m.mariani at imola.nettuno.it>
> Which one is more ugly?

> c = curs.fetchone()
> while c:
>         print c
>         c = curs.fetchone()

> while 1:
>         c = curs.fetchone()
>         if c:
>                 print c
>         else:
>                 break

  The usual answers when this is asked (quick, checking if this is
in the FAQ as it is a faq -- nope) are:

1) "The first is uglier as you have needless duplication of
code"

2) """I wish Python could do

  while (c = curs.fetchone()):
    print c
"""

 To which the response is, it isn't worth the consequences of
making hard-to-catch errors like

  while (c == curs.fetchone()):
    print c

3) "You quickly get used to it"


4) "Try rewriting your code to use __getitem__"

For you specific example you really want to have something like:

a)
  for c in curs:
     print c

b) or maybe

  for c in curs.fetchall()

c) or how about (warning: untested code ahead)

class ForwardIterate:
  def __init__(self, callable):
    self._callable = callable
    self._i = 0
  def __getitem__(self, n):
    assert(self._i == n)   # probably being overly paranoid...
    self._i = self._i + 1
    return callable()

for c in ForwardIterate(curs.fetchone):
    print c


5) "Oh, and then there's Evan Simpson's PITA"

    http://www.dejanews.com/getdoc.xp?AN=429491196


6) "This has been discussed many times in the newsgroup before so stop
the thread."

In other words, searching DejaNews for the thread "Assignment in
Conditional" I found 248 articles in it.


						Andrew Dalke
						"And hi to you Jeff!"
						dalke at bioreason.com




More information about the Python-list mailing list