For review: PEP 308 - If-then-else expression

Andrew Koenig ark at research.att.com
Sat Feb 8 17:51:53 CET 2003


James> Consider

James>     y = (x ** 2, 2.0 * x - 1.0)[x > 1.0]

James> By observing that this is a special case of a tuple "literal"
James> followed immediately by a selector it becomes apparent that
James> only one of the expressions is actually needed and that the
James> tuple construction and evaluation of all of the expression
James> elements is unnecessary and can be optimized away to leave,
James> after evaluation of the selector, a need to evaluate only one
James> expression.  This would allow the evaluation of only one of the
James> expressions in the tuple and provide the equivalent of "short
James> circuit" evaluation.

Allow, but not require.  I think that's a bad idea.

The reason is this:  Suppose instead that you had written this:

        y = (sqrt(x), 0.0)[x < 0]

The idea, of course, is to avoid trying to compute the square root of
a negative value.

But if whether sqrt(x) is evaluated depends on an optimization,
then this code will work on some implementations and fail on others.
Even worse:  If you're using an implementation on which it works,
no amount of testing will ever reveal the failure.

So I really, really, really, really, really don't want to leave
it up to the implementation whether to evaluate unused parts
of tuples -- unless that choice is firmly tied to the optimization
flag so I can force it one way or the other for testing purposes.


-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark




More information about the Python-list mailing list