Conditional operator in Python?

Erik Max Francis max at alcyone.com
Sun Apr 1 00:22:54 EST 2001


Rainer Deyke wrote:

> This is not equivalent in the general case.
> 
> 0 ? 0 : 1    --> 0
> 0 and 0 or 1 --> 1

Indeed, which negates most of the benefit of trying to use such a
substituted expression in Python -- the conditional operator is useful
because it is straightforward and clear.  The Python FAQ, for instance,
suggests x ? a : b can be reliably substituted with

    (x and [a] or [b])[0]

which definitely works ([a] and [b] are singleton lists and always
evaluate true), but it makes the meaning unclear enough to defeat the
purpose of wanting to use a conditional operator in the first place.

For cases where I know that the testing value will be a "boolean" (0 or
1 and nothing else), I generally do something like

    [a, b][x]

which ain't great but is better than the former.

Still, one can hope.

On a vaguely related subject, why is there no Boolean type in Python? 
Seems like it would clean things up a great deal -- my understanding is
that there is even an internal Python Boolean type, but it is hidden in
the interpreter.  How come?

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ If I had known, I would have become a watchmaker.
\__/ Albert Einstein
    blackgirl international / http://www.blackgirl.org/
 The Internet resource for black women.



More information about the Python-list mailing list