Towards a more Pythonic "Ternary Operator"
Dennis Reinhardt
DennisR at dair.com
Tue Mar 4 21:14:06 EST 2003
> If we can all agree that
> this is a weakness of Python, then we can look of various ways
> to solve the problem.
The weakness is that Python has a "dangling else" ambiguity which requires
indentation to disambiguate (i.e. the if-else must occupy two lines
minimum).
One would like to write something like
A = if <cond> then B else C endif (not Python!)
Ignoring the assignment for awhile, can get close to a one-liner if with
if <cond>: B; else: C (not valid Python)
Arguably (and incorrectly argued), the ";" allows this to be written as a
one-liner To see why this can never be valid Python, consider nesting "if
<cond2>: D" for B to yield:
if <cond>: if <cond2>: D; else: C
It is truly ambiguous whether this parses as:
if <cond>:
if <cond2>: D;
else: C
or
if <cond>:
if <cond2>: D;
else: C
The solution I see for resolving "dangling else" is to put a token at the
end, just as I have in the "endif" in the first example (this example is
from PLD2, a language I designed). I think tacking something onto if-end is
impractical without something new tacked on at the beginning to notify the
interpreter to parse for the something on the end.
>From where I sit, resolving "dangling else" in Python without indentation
just introduces cruft into the language. There are things my language will
not do well. A single-line "if" does not look like a good fit in Python.
I would be inclined here to not change anything.
> <variable> = ( if <condition>:
> <value-a>
> else:
> <value-b>
> )
I presume that
<variable> = ( if <condition>: value-s>)
is also allowed. Does this extend to
<variable> = subroutine_call(( if <condition>: value-s>))
Where the outer parens show that subroutine_call is being invoked and inner
parens show if expression is being evaluated.
--
Dennis Reinhardt
http://www.spamai.com
More information about the Python-list
mailing list