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

Peter Schwalm peter.schwalm at epost.de
Tue Feb 18 18:04:26 CET 2003


Guido van Rossum <guido at python.org> wrote in message news:<mailman.1044638179.4983.python-list at python.org>...
 
>     The proposed syntax is as follows:
> 
>         <expression1> if <condition> else <expression2>
> 
...

For me there are some points to consider:

- I'm a c/c++ veteran and have no difficulties reading a ternary operator
like "?:". Although it might look weird for many people, I often prefer
not to spread the handling of alternatives into statements instead of
doing it in the expression itself. Using if-else statements would often
lead to repetion of code. For example I would not like to code a
complicated printf() twice only because a single argument has two
alternatives.

- In python I often use the construct

	"(else, if) [condition]"

instead of "?:". But this has two disadvantages:

	a) both alternatives are evaluated. This is not always tolerable.
	b) it is somewhat counter-intuitive because the "if" and "else"-
	   parts inside the sequence are in the "wrong" order.

On the other hand I like this construct because it is *more general*
than "?:". Instead of using a truth value as an index, one can use
*any* integer value as an index. So we not only have an "if ... else"
inside expressions, but also the more general "if ... elif ... else"
which IMHO is much more intuitive than nested "if"s -- in statements as
well as in expressions.

Given that, I ask myself, if it would not be possible to have such a
multi-selection in expressions but without the disadvantage of all
alternatives being evaluated (like in "(else, if) [condition]").

This might be accomplished with something like a
"lazy-evaluation sequence" -- a sequence the members of which are only
evualated by a subscript operation.

>From Parzival Herzog's contribution to this discussion I know one can
achieve this effect by using lambdas as sequence members like in

	(lambda ifPart, lambda elsePart) [condition]

but
	a) I think this looks really weird and
	b) I suppose it is very inefficient.

I also believe that such a "lazy-evaluation sequence" would not hurt the
spirit of Python because Python is already very strong in processing
sequences like tuples, lists and now generators.

I'm not sure if such a construct can be introduced into Python, but if
it's possible, IMHO it would be better to abandon a ternary operator
and instead introduce the more general and powerful concept of a lazy
sequence. I think both constructs aren't very intuitive. Given that I
would introduce only the more powerful concept.

Peter Schwalm




More information about the Python-list mailing list