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

Steve Holden sholden at holdenweb.com
Tue Jun 4 12:47:54 EDT 2002


----- Original Message -----
From: "Jeff Epler" <jepler at unpythonic.net>
To: "Steve Holden" <sholden at holdenweb.com>
Cc: <python-list at python.org>
Sent: Tuesday, June 04, 2002 12:28 PM
Subject: Re: Behavior of += (was Re: [Python-Dev] Customization docs)


> 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
>
Interesting. But there was no need to call me a sucker.

> 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....
>
It wouldn't be the oddest I've ever taken, but now you have clarified your
assertion I understand what you were saying.

> > 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.
>
Indeed, I now understand exactly why the error occurs. I have to say I still
think that the existing behavior is reasonable.

> 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.
>
Possibly. In fact it seems to me that it's only *because* a rebinding does
in fact take place that the tuple element assignment fails, so it's just as
well it does.

There's no point hating augmented assignment. Just don't use it if you find
it gives confusing results.

happy-when-i-didn't-understand-and-happy-now-i-do'ly y'rs  - steve
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list