[docs] [issue16701] Docs missing the behavior of += (in-place add) for lists.

benrg report at bugs.python.org
Thu Jan 24 19:40:16 CET 2013


benrg added the comment:

> AFAIK in C "x += 1" is equivalent to "x++", and both are semantically
> more about incrementing (mutating) the value of x than about creating a
> new value that gets assigned to x. Likewise it seems to me more natural
> to interpret "x += y" as "add the value of y to the object x" than "add
> x and y together and save the result in x".

Look, it's very simple: in C, ++x and x += 1 and x = x + 1 all mean the same thing. You can argue about how to describe the thing that they do, but there's only one thing to describe. Likewise, in every other language that borrows the op= syntax from C, it is a shorthand for the expanded version with the bare operator. As far as I know, Python is the only exception. If you know of another exception please say so.


> >>> x = ([],)
> >>> x[0] += [1]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'tuple' object does not support item assignment
> >>> x
> ([1],)

I actually knew about this. It's an understandably difficult corner case, since the exception is raised after __iadd__ returns, so there's no chance for it to roll back its changes.

At least, I thought it was a difficult corner case back when I thought the in-place update was a mere optimization. But if += really means .extend() on lists, this should not raise an exception at all. In fact there's no sense in having __iadd__ return a value that gets assigned anywhere, since mutable objects always mutate and return themselves and immutable objects don't define __iadd__. It looks like the interface was designed with the standard semantics in mind but the implementation did something different, leaving a vestigial assignment that's always a no-op. What a disaster.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16701>
_______________________________________


More information about the docs mailing list