Conditional operator in Python?

Clark C. Evans cce at clarkevans.com
Fri Apr 6 21:07:33 EDT 2001


On Tue, 3 Apr 2001, Michael Chermside wrote:
> >     (x and [a] or [b])[0]
> 
> 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?

This works as long as trueval and falseval do not have 
side-effects.  As you point out, this doesn't short-circut.

>>> def x():
...   print "x"
...   return "x"
...
>>> def y():
...   print "y"
...   return "y"
...
>>> def cond(test,tv,fv):
...   if test:
...      return tv
...   else:
...      return fv
...
>>> cond(0,x(),y())
x
y
'y'
>>> (0 and [x()] or [y()])[0]
y
'y'






More information about the Python-list mailing list