Ternery operator

Richie Hindle richie at entrian.com
Tue Sep 9 14:37:12 CEST 2003


[Uwe]
> Normaly you should simulate "C ? T : F"
> 
> either by
>              [T,F][not C]
> 
> or
> 
>              (C and [T] or [F])[0]
> 
> in the first case T and F are evaluated allways,
> the latter solution does short circuit evaluation,
> which is according to the C/C++ semantics of the
> ternary operator.

[Michael, shouting]
> NOT TRUE!
> 
> NEITHER of your options does short-circuit evaluation.

Er:

>>> def one():
	print 1
	return 1

>>> def two():
	print 2
	return 2

>>> (True and [one()] or [two()])[0]
1
1
>>> (False and [one()] or [two()])[0]
2
2
>>> 

So it's lazy in the sense of "will not execute the branch not taken",
which is I'm sure what Uwe meant.  But it's also over-eager in the sense
of "may execute the taken branch multiple times."

[Not condoning the use of this idiom, just correcting a factual error.]

-- 
Richie Hindle
richie at entrian.com






More information about the Python-list mailing list