parse-time optimizations

Roeland Rengelink r.b.rigilink at chello.nl
Thu May 31 17:08:42 EDT 2001


Joshua Marshall wrote:
> 
> Carlos Ribeiro <cribeiro at mail.inet.com.br> wrote:
> >> >     x + 1 + 2 + 3
> >>
> >> > couldn't even be folded down to
> >>
> >> >     x + 1 + 5
> >>
> >>This is an unambiguous situation.
> 
> > No, it is not unambiguous. It assumes that the + operator is associative -
> > which is true for the case of the "normal" addition. However, due to
> > Python's dynamic nature, x can be any kind of object. It can define a new
> > addition operation without the nice properties we all take for granted.
> 
> I didn't realize this was possible in Python.  Can you give an example
> of how a new, right-associative addition operator could 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>


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