parse-time optimizations

jcm grumble at usa.net
Fri Jun 1 04:32:10 CEST 2001


Roeland Rengelink <r.b.rigilink at chello.nl> wrote:

> For right associative, use __radd__:

> class X:
>     def __radd__(self, other):
>         print 'Hi', other
>         return X()

> x = X()
> y = 1+2+3+x

> giving:

> Hi 6.

This is still left associative (the "1+2" happens first, instead of
the "3+x").  It's just that the custom object is on the right side of
an operator.

> Python's evaluation is left to right, Hence

The + operator has this behavior (left associativity).  The **
operator, on the other hand, is right-associative.

> y = 1+2+3+x

> equals

> y = 6+x

> Since  6+x raises a TypeError, this will be evaluated using

> y = x.__radd__(6)

> Roeland



More information about the Python-list mailing list