Behavior of += (was Re: [Python-Dev] Customization docs)

Jeff Epler jepler at unpythonic.net
Tue Jun 4 12:28:25 EDT 2002


On Tue, Jun 04, 2002 at 12:01:56PM -0400, Steve Holden wrote:
> >>> a = b = [1,2,3]
> >>> a += [4]
> >>> a, id(a), b, id(b)
> ([1, 2, 3, 4], 269472088, [1, 2, 3, 4], 269472088)
> >>>
> 
> Where did the rebinding take place? ISTM that "a" is still bound to the same
> list, which has been modified in place.

Sure it rebinds a (just to the same object formerly bound to it) ..
>>> class X:
...     def __setattr__(self, a, v):
...         print "rebinding %s, sucker" % a
...         self.__dict__[a] = v
... 
>>> x = X() 
>>> x.a = b = [1,2,3]
rebinding a, sucker
>>> x.a += [4]
rebinding a, sucker
>>> x.a is b
True

Or are you saying that in
    a = b = [1,2,3]
    a = b
the second statement isn't a rebinding operation?  That seems like an
odd position to take....

> Clearly an explicit assignment to a tuple element is always going to fail,
> so I don't really see what this would tell you.

But you're claiming that there *is* no binding, so it would be
surprising that this augmented assignment wouldn't work
    >>> t = ([1])
    >>> t[0] += [2]
t[0] "isn't" being rebound (according to your above logic, since if the
operation could complete, the "is" relation would hold between old t[0]
and new t[0]) .. but, of course, this actually causes a traceback.

I hate augmented assignment more and more each day, but at least I think
I understand it.  Your claim that there is no rebinding operation makes
me think that you may not.

Jeff





More information about the Python-list mailing list