Conditional operator in Python?

thp at cs.ucr.edu thp at cs.ucr.edu
Tue Sep 4 02:07:49 EDT 2001


Terry Reedy <tjreedy at home.com> wrote:

: <thp at cs.ucr.edu> wrote in message news:9n1hr7$7op$1 at glue.ucr.edu...
:> Marcin 'Qrczak' Kowalczyk <qrczak at knm.org.pl> wrote:
:> : Sat, 31 Mar 2001 21:22:54 -0800, Erik Max Francis
: <max at alcyone.com> pisze:
:>
:> :> The Python FAQ, for instance, suggests x ? a : b can be reliably
:> :> substituted with
:> :>
:> :>     (x and [a] or [b])[0]

: If you *know* that a will always evaluate as <true>, then 'x and a or
: b' works fine.  All the rigamarole of tuples or lambdas is only needed
: to protect against the possibility of a evaulating as false.  When it
: is not possible, said protection is not necessary.

:> Agreed.  Something more aesthetic is definitely needed.  I hate
: writing:
:>
:>   factorial = lambda x : (x<=1 and [1] or [x*factorial(x-1)])[0]

: Since 1 != 0, quite dependably, you do not need to. try "x<=1 and 1 or
: x*factorial(x-1)"

Agreed.  That helps in this particular case, but:
  - Correctness depends on the second operand being nonzero, which
    is not determinable in the general case.
  - It's still less aesthetic than the common ?: syntax.
  - It's still a hack (but a less ugly one).
A more elegant syntax is badly needed.

Tom Payne
















More information about the Python-list mailing list