ternary operator

David Gausebeck gausebec-spam at paypal.com
Fri Feb 7 03:02:58 CET 2003


>> You like (b, c)[not a] better?  I generally don't write code like
>
>Nope. I like
>
>    if a:
>        x =3D b
>    else:
>        x =3D c
>
>In fact, I have written into the Python style guide for my team =
>explicitly to not write things like
>
>    if a: x =3D b
>    else: x =3D c
>
>for much the same reason that I specify to not write
>
>    if (a)
>        x =3D b;
>    else
>        x =3D c;
>
>or
>
>    if (a) x =3D b;
>    else x =3D c;
>
>in C.

I agree that the style you're promoting makes the logic clearer.
However, my main goal is the clarity of the code as a whole, not of
each part.  IMO, something like

   if zipped:
      extension = "tar.gz"
   else:
      extension = "tar"
   print "Processed %s.%s" % (filename, extension)

is less clear than

   print "Processed %s.%s" % (filename, zipped ? "tar.gz" : "tar")

because the bulk of the space is taken up by code that's not central
to what's actually being done.  When I look at the first case, the
main thing I see is not the print line; it's the code to select an
extension.  When I look at the second case, it's immediately obvious
that the code is printing a status message.

If I want to look at the code closely and see exactly how the status
message is being generated, the second case takes a little more
effort.  But most of the time when I'm looking at the code I won't
care about the details of the status message, and the extra bulk (5x
expansion in number of lines for this case) makes it harder to see
what's going on overall.

-Dave




More information about the Python-list mailing list