Trying to understand += better

Lie Ryan lie.1296 at
Mon Nov 23 04:28:17 CET 2009

Roy Smith wrote:
> If I've got an object foo, and I execute:
> += baz
> exactly what happens if foo does not have a 'bar' attribute?  It's
> pretty clear that foo.__getattr__('bar') gets called first, but it's a
> little murky after that.  Assume for the moment that foo.__getattr__
> ('bar') returns an object x.  I think the complete sequence of calls
> is:
> foo.__getattr__('bar')  ==> x
> x.__add__(baz)  ==> y
> foo.__setattr__('bar', y)
> but I'm not 100% sure.  It would be nice if it was, because that would
> let me do some very neat magic in a system I'm working on :-)
> How would things change if X defined __iadd__()?

The semantic of the in-place operator is something like:
x += y
x = x.__iadd__(y)

thus += baz
becomes =

So the call sequence is,
foo.__getattr__('bar') ==> x
x.__iadd__(baz) ==> y
foo.__setattr__('bar', y)

the default definition of object.__iadd__ is something like this:
def __iadd__(self, other):
     # this calls self.__add__ or other.__radd__ according to the
     # operator call rule, may call __coerce__ or any other magics
     # in operator calling
     return self + other

More information about the Python-list mailing list