Equivalent to (a ? b : c) ?

Justin Sheehy dworkin at ccs.neu.edu
Thu Dec 23 10:44:13 EST 1999


Anders M Eriksson <anders.eriksson at morateknikutveckling.se> writes:

> >    def ternaryif(a, b, c):
> >	if a: return b
> >	return c

> Now I'm confused!  in the ternaryif function how will both b and c be
> evaluated?

Not even in the function, but before it really starts.  :-)  Before `a'
is even tested for truth or falsity, all three parameters have been
evaluated.  In the case where the parameters are simple data types,
this doesn't matter.  But if evaluating them causes side effects, it
is important.

If I called ternaryif like this:

ternaryif(somevalue, Bfunc(), Cfunc())

The variables b and c would be set to the values returned by these 
functions.  Regardless of the value of `somevalue', both Bfunc()
and Cfunc() have already been executed.

This is very different from a short-circuiting operator.

-Justin

 



More information about the Python-list mailing list