parse-time optimizations

Roeland Rengelink r.b.rigilink at chello.nl
Fri Jun 1 02:24:02 CEST 2001


jcm wrote:
> 
> Roeland Rengelink <r.b.rigilink at chello.nl> wrote:
> 
> > jcm> I didn't realize this was possible in Python.  Can you give an
> > jcm> example of how a new, right-associative addition operator could
> > jcm> be defined?
> 
> > well, more asocial than associative, but:
> 
> > class X:
> >     def __add__(self, other):
> >         print 'Hi', other
> >         return X()
> 
> > x = X()
> > y = x+1+2+3
> > print y
> 
> > gives:
> 
> > Hi 1
> > Hi 2
> > Hi 3
> > <__main__.X instance at 0x80cefa4>
> 
> > and shouldn't give
> 
> > Hi 6
> > <__main__.X instance at 0x80cefa4>
> 
> Sure, this was covered already--plus is left-associative.  Another
> poster implied that in Python you can redefine plus so that it is
> right-associative for a custom type.  Or maybe I misinterpreted him.

I should have read everything.

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.

Python's evaluation is left to right, Hence

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



-- 
r.b.rigilink at chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"



More information about the Python-list mailing list