[Python-Dev] PEP 308: "then" "else" for deprecating "and" "or" side effects
Piet van Oostrum
piet at cs.uu.nl
Sun Feb 16 11:17:05 EST 2003
>>>>> Gary Herron <gherron at islandtraining.com> (GH) wrote:
GH> The above defines two binary operators "then" and "else" and a ternary
GH> operator "then...else". The question which occurred to me is: Since
GH> the ternary operator is formed by what looks like two binary
GH> operators, can the action of the ternary operator be defined in terms
GH> of the actions of the two binary operators. In other words, does the
GH> expression:
GH> a then b else c # the ternary operator
GH> evaluate as either
GH> a then (b else c) # two binary operators
GH> or
GH> (a then b) else c # two binary operators
GH> The answer is *NO*, all three expressions evaluate to different
GH> results. More on that below.
GH> Now we are used to disambiguating expressions with multiple binary
GH> operators by considering the precedence and (left or right)
GH> associativity of the operators involved. That is (a-b-c) evaluates as
GH> (a-b)-c and (a+b*c) evaluates as a+(b*c). However, in this
GH> "then...else" expression, something which looks like (and could be
GH> legitimately parsed as) two binary operations, in fact cannot be
GH> disambiguated by either application of parentheses and must be treated
GH> as a ternary operator.
You can define them as binary operators if you use a little different
definitions. Supposing 'then' has higher precedence then 'else'
(parentheses added for clarity):
def __then__(a,b):
if a:
return (b,)
else:
return False
def __else__(b,c):
if b:
return b[0]
else:
return c
Of course you must imagine the laziness.
Even with 'else' having higher precedence then 'then' it is possible, but
you will loose laziness:
def __else__(b,c):
return (b,c)
def __then__(a,b):
return b[not a]
And the laziness could even be added if the compiler would do something
like:
def __else__(b,c):
return (lambda: b, lambda: c)
def __then__(a,b):
return b[not a]()
interpreted as macros rather than functions.
--
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl
More information about the Python-list
mailing list