Conditional operator in Python?

Michael Chermside mcherm at destiny.com
Tue Apr 3 23:01:03 EDT 2001


> > > Why isn't there a conditional operator (a ? b : c) in Python?

  [stuff about   (cond and trueVal or falseVal) ]

> > 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.
> 

Hey... it's a good question. Tools like list comprehensions make it
quite easy to use a functional style with python code for a lot of
things, and it's very useful tool. But that's where the need for a
conditional statement is strongest. Of course it's not necessary...
I use

    def cond(test, trueval, falseval):
        if test:
            return trueval
        else:
            return falseval

a bit. But it'd be more convenient if there were a true, 
short-circuiting version available. Are there any good reasons
NOT do do so? (The uglyness of "?:" is not a valid reason... I
KNOW the Python community can find a cleaner syntax.) One obvious
reason is that it adds yet one more control structure to the
language (which we want to keep small), but are there any other
reasons you can think of?

-- Michael Chermside




More information about the Python-list mailing list