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

Andrew Barnert abarnert at yahoo.com
Sat Feb 14 01:12:11 CET 2015


On Feb 13, 2015, at 8:02, Chris Barker - NOAA Federal <chris.barker at noaa.gov> wrote:

>> On Feb 12, 2015, at 10:24 PM, Steven D'Aprano <steve at pearwood.info> 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.)


More information about the Python-ideas mailing list