Re: Adding "+" and "+=" operators to dict 
[Posted March 4, 2015 by jake]
               
               
 
| From: |  | Andrew Barnert <abarnert-/E1597aS9LTXhkTzDaz57MHxdsOJtyKN-AT-public.gmane.org> | 
| To: |  | Chris Barker - NOAA Federal <chris.barker-32lpuo7BZBA-AT-public.gmane.org> | 
| Subject: |  | Re: Adding "+" and "+=" operators to dict | 
| Date: |  | Fri, 13 Feb 2015 16:12:11 -0800 | 
| Message-ID: |  | <81E99F71-29C3-41CE-B53F-8D2102E689E4@yahoo.com> | 
| Cc: |  | "python-ideas-+ZN9ApsXKcEdnm+yROfE0A-AT-public.gmane.org" <python-ideas-+ZN9ApsXKcEdnm+yROfE0A-AT-public.gmane.org> | 
On Feb 13, 2015, at 8:02, Chris Barker - NOAA Federal <chris.barker-32lpuo7BZBA@public.gmane.org>
wrote:
>> On Feb 12, 2015, at 10:24 PM, Steven D'Aprano <steve-iDnA/YwAAsAk+I/owrrOrA@public.gmane.org>
wrote:
>>> += duplicates the extend method on lists.
>> 
>> Yes it does, and that sometimes causes confusion when people wonder why
>> alist += blist is not *quite* the same as alist = alist + blist.
> 
> Actually, that's the primary motivator for += and friends -- to
> support in-place operations on mutables. Notably numpy arrays.
> 
>> It also
>> leads to a quite ugly and unfortunate language wart with tuples:
>> 
>> py> t = ([], None)
>> py> t[0] += [1]
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> TypeError: 'tuple' object does not support item assignment
>> py> t
>> ([1], None)
>> 
>> Try explaining to novices why this is not a bug.
> 
> I'm going to have to think about that a fair bit myself -- so yes,
> really confusing.
> 
> But the "problem" here is that augmented assignment shouldn't work on
> immutables at all.
The problem is that the way augmented assignment works is to first treat the target as an
expression, then call __iadd__ on the result, then assign the result of that back to the target. So
your "t[0] == [1]" turns into, in effect, "setitem(t, 0, getitem(t, 0).__iadd__([1]))". Once you
see it that way, it's obvious why it works the way it does. And the official FAQ explains this, but
it still seems to surprise plenty of people who aren't at even close to novices. (But that's
probably more relevant to the other thread on namespace unpacking than to this thread.)
_______________________________________________
Python-ideas mailing list
Python-ideas-+ZN9ApsXKcEdnm+yROfE0A@public.gmane.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/