Towards a more Pythonic "Ternary Operator"
Alex Martelli
aleax at aleax.it
Tue Mar 4 10:05:12 EST 2003
Clark C. Evans wrote:
> I was thinking, perhaps if people first agreed on the problem
> finding a solution could become more of a detail. Here is a
> stab at the 'terinary operator' problem.
>
> Consider the following two constructs, ignoring the syntax
> details for a moment:
>
> if <condition>:
> <variable> = <value-a> # first assignment
> else:
> <variable> = <value-b> # second assignment
>
> In this example, the first and second assignment have
> a parallel structure; but the '<variable> =' part happens
> to be duplicated. This is somewhat inefficient for
> two reasons:
>
> (a) someone reading the code has to scan the whole
> structure and determine that there is a parallel
> structure, where the variable is assigned a value
> in either case of the condition; and
>
> (b) someone writing/editing the code has to make sure
> that the variable is the same in both places or
> else the parallel structure is broken.
Good points -- basically similar to arguments for having
such augmented-assignment operators as += in the language
(avoiding <variable> = <variable> <operator> <value>
redundancy both in reading and writing the code).
> Besides the left hand side of the assignment, there happens
> to be another parallel structure which occurs often...
>
> if a == X:
> b = Q
> elif a == Y:
> b = R
> else:
> b = S
>
> In this case, not only is 'b = ' duplicated three times,
> but 'a ==' is duplicated twice. These two can be combined
Hmmm, well, yes, but this is somewhat less convincing to me.
> into the select/case pattern:
>
> b = select a:
> case X: Q
> case Y: R
> else: S
>
> So, really, we have two categories of duplication:
>
> (a) the left hand side of the assignment
> (b) the left hand side of the conditional
Yes, but they're orthogonal -- i.e. the second case might
just as well be:
if a == X:
c = Q
elif a == Y:
d = R
else:
e = S
which only shows redundancy kind [b], not kind [a]. Why
are we assuming the two redundancies go together?
> Perhaps we can scratch two itches at the same time? The syntax
> really doesn't matter now; what matters is that we agree on the
> problem. Then we can throw up our best syntaxes and let Guido
> choose and work his magic...
I like this analysis, but I do not understand the reason to
assume the two redundancy problems should occur together.
Alex
More information about the Python-list
mailing list