[Python-ideas] Adding "+" and "+=" operators to dict

Rob Cliffe rob.cliffe at btinternet.com
Sat Feb 14 01:51:43 CET 2015


On 13/02/2015 06:19, Steven D'Aprano wrote:
> On Thu, Feb 12, 2015 at 07:43:36PM -0800, Chris Barker - NOAA Federal wrote:
>>> avoids any confusion over operators and having += duplicating the
>>> update method.
>> += 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. 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.
Er, I'm not a novice, but why isn't that a bug?  I would have expected t 
to be altered as shown without raising an exception. (And given that the 
code does raise an exception, I find it surprising that it otherwise has 
the presumably intended effect.) t[0] is a list, not a tuple, so I would 
expect it to behave as a list:

 >>> L = t[0]
 >>> L += [2]
 >>> t
([1,2], None)

I was also curious why you say that alist += blist is not quite the same 
as alist = alist + blist.
(So far I've worked out that the first uses __iadd__ and the second uses 
__add__.  And there is probably a performance difference.  And the 
semantics could be different for objects of a custom class, but as far 
as I can see they should be the same for list objects.  What have I missed?)
I would appreciate it if you or someone else can find the time to answer.
Rob Cliffe




More information about the Python-ideas mailing list