For review: PEP 308 - If-then-else expression

Dan Schmidt dfan at dfan.org
Fri Feb 7 21:00:30 CET 2003


I am so keen on having a ternary operator in Python that I would
probably vote yes on any proposal that was made.

I dislike

  if test:
      x = a
  else:
      x = b

not because it is longer than

  x = a if test else b

but because I think the intent of the code is much more clear if one
says "x is the result of this computation depending on test" than if
one says "if test is true, evaluate this body of code, otherwise
evaluate this other body, and by the way they both happen to assign a
value to x."  My appreciation for the former comes partly from using
languages like Lisp, where there is no distinction between statements
and expressions, and partly from using functional languages, where
you really do have to decide what x is going to be all in one fell
swoop.  I find that putting the logic for computing x in one place
leads to fewer errors (for one thing, you don't have to type 'x'
twice).

OK, so I would probably vote 'yes' on almost any proposal, but seriously,
this one seems fine to me.  The order of operands seemed weird at first,
but I kind of like the fact that when you're reading the code, "a if
test else b" reads like a noun, because the first thing you encounter
is 'a' rather than the test.  That is much more 'Englishy' to me than
encountering the condition first.

I don't worry so much about the way this can be abused by putting in
the middle of other expressions as in Guido's examples.  There are
plenty of language constructs that you can abuse if you try hard
enough, even in Python.

Dan

-- 
http://www.dfan.org




More information about the Python-list mailing list