Assignment and comparison in one statement

Carl Banks pavlovevidence at gmail.com
Sat May 24 21:15:39 EDT 2008


On May 24, 7:12 am, Johannes Bauer <dfnsonfsdu... at gmx.de> wrote:
> Carl Banks schrieb:
>
> > p = myfunction()
> > if p:
> >     print p
>
> > (I recommend doing it this way in C, too.)
>
> This is okay for if-clauses, but sucks for while-loops:
>
> while (fgets(buf, sizeof(buf), f)) {
>         printf("%s\n", buf);
>
> }


In earlier times, the Python idiom was this:

while True:
    line = f.readline()
    if not line:
        break
    print line

Not the prettiest thing ever, but it works fine, is readable, and
avoids a temporary variable.  In C, given the choice between this or
using assignment expression, I'd say use either one.  (But don't use
the version with a temporary, that's ugly as hell.)

More recent versions of Python have obviated the need to use this
idiom by making it possible to iterate over the lines of a file
directly.  First they added xreadlines:

for line in xreadlines(f):
    print line

Then they deprecated the xreadline function and made it a method:

for line in f.xreadlines():
    print line

Then they recommended you no longer use that, and just made file
objects directly iterable:

for line in f:
    print line

The point is, the Python language developers do share your concern
about these things.  However, they still think assignment epxressions
are a very bad idea, so they've sought other solutions to these
issues.

(But, as I said, they have yet to provide an alternative for elif
clauses; you're stuck with workarounds there.)


Carl Banks



More information about the Python-list mailing list