[Python-ideas] PEP: Dict addition and subtraction

Guido van Rossum guido at python.org
Mon Mar 4 18:57:38 EST 2019


On Mon, Mar 4, 2019 at 3:31 PM Del Gan <delgan.py at gmail.com> wrote:

> > the augmented assignment version allows anything the ``update`` method
> allows, such as iterables of key/value pairs
>
> I am a little surprised by this choice.
>
> First, this means that "a += b" would not be equivalent to "a = a +
> b". Is there other built-in types which act differently if called with
> the operator or augmented assignment version?
>

Yes. The same happens for lists. [1] + 'a' is a TypeError, but a += 'a'
works:

>>> a = [1]
>>> a + 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> a += 'a'
>>> a
[1, 'a']
>>>


> Secondly, that would imply I would no longer be able to infer the type
> of "a" while reading "a += [('foo', 'bar')]". Is it a list? A dict?
>

Real code more likely looks like "a += b" and there you already don't have
much of a clue -- the author of the code should probably communicate this
using naming conventions or type annotations.


> Those two points make me uncomfortable with "+=" strictly behaving
> like ".update()".
>

And yet that's how it works for lists. (Note that dict.update() still has
capabilities beyond +=, since you can also invoke it with keyword args.)

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190304/26e930f0/attachment-0001.html>


More information about the Python-ideas mailing list