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

James P. Rutledge jrut at spamcop.net
Sat Feb 8 10:05:20 EST 2003


As Dan Schmidt rightly pointed out my first example was indeed
incorrect.  It does appear that those of us whose prior experience with
conditional expressions is from the C language tend to expect the first
alternative expression to be associated with the True condition.

However, if there is to be use of an idiom for conditional expressions,
(which is, of course, questionable) should it be a new language
construct or should it be an existing construct?

Will experience in using the existing construct quickly overcome habits
carried over from previous languages or will there be a continuous
problem with errors?

It would be a matter of getting accustomed to the meaning

    (expression_if_false, expression__if_true)[condition]

The advantage of using something like

    ("text", "html")[is_html()]

is that it is already correct syntax.

Consider

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

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

In any case, in general I would tend to favor not adding a conditional
expression to the language.

-Jim


-Jim





More information about the Python-list mailing list