Towards a more Pythonic "Ternary Operator"
Clark C. Evans
cce at clarkevans.com
Tue Mar 4 14:06:02 CET 2003
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:
<variable> = <value-a> # first assignment
<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
(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.
Compare this example to the following...
<variable> = ( if <condition>:
In this case, the data-duplication is eliminated; for this
particular syntax we trade additional indentation and
parenthesis for the pleasure of only having to write the
variable once. The result:
(a) someone reading the structure can immediately
see that the goal of the fragment is to assign
a value to the variable, in all cases.
(b) someone writing/editing the structure need only
type the variable name once; the compiler worries
about maintaining the parallel structure.
In summary, people want a way to make a conditional structure
'subordinate' to an assignment. So. If we can all agree that
this is a weakness of Python, then we can look of various ways
to solve the problem. Perhaps a "terinary operator" isn't
the best way to do it.
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
b = S
In this case, not only is 'b = ' duplicated three times,
but 'a ==' is duplicated twice. These two can be combined
into the select/case pattern:
b = select a:
case X: Q
case Y: R
So, really, we have two categories of duplication:
(a) the left hand side of the assignment
(b) the left hand side of the conditional
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...
More information about the Python-list