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

Steven D'Aprano steve at pearwood.info
Fri Feb 13 03:45:22 CET 2015


On Thu, Feb 12, 2015 at 07:25:24PM -0700, Eric Snow wrote:

> Or just make "dict(a, b, c)" work.

I've come to the same conclusion.

Pros:

- No more arguments about which operator is more intuitive, whether 
  commutativity or associativity is more important, etc. It's just a 
  short, simple function call.

- Left-to-right semantics are obvious to anyone who reads left-to-right.

- No new methods or built-in functions needed.

- Want a subclass? Just call it instead of dict: MyDict(a, b, c). This 
  should even work with OrderedDict, modulo the usual 
  dicts-are-unordered issues.

- Like dict.update, this can support iterables of (key,value) 
  pairs, and optional keyword args.

- dict.update should also be extended to support multiple mappings.

- No pathologically slow performance from repeated addition.

- Although the names are slightly different, we have symmetry between 
  update-in-place using the update method, and copy-and-update using the 
  dict constructor.

- Surely this change is minor enough that it doesn't need a PEP? It just
  needs a patch and approval from a senior developer with commit 
  privileges.


Cons:

- dict(a,b,c,d) takes 6 characters more to write than a+b+c+d.

- Doesn't support the less common merge semantics to deal with 
  duplicate keys, such as adding the values. But then neither would
  a + operator.

- The implementation for immutable mappings is not obvious. We can't 
  literally define the semantics in terms of update, since 
  Mapping.update doesn't exist:


py> from collections import Mapping, MutableMapping
py> Mapping.update
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Mapping' has no attribute 'update'
py> MutableMapping.update
<function MutableMapping.update at 0xb7c1353c>





-- 
Steven


More information about the Python-ideas mailing list