[Python-ideas] dict.merge(d1, d2, ...) (Counter proposal for PEP 584)

INADA Naoki songofacandy at gmail.com
Tue Mar 5 02:39:40 EST 2019

I think some people in favor of PEP 584 just want
single expression for merging dicts without in-place update.

But I feel it's abuse of operator overload.  I think functions
and methods are better than operator unless the operator
has good math metaphor, or very frequently used as concatenate

This is why function and methods are better:

* Easy to search.
* Name can describe it's behavior better than abused operator.
* Simpler lookup behavior. (e.g. subclass and __iadd__)

Then, I propose `dict.merge` method.  It is outer-place version
of `dict.update`, but accepts multiple dicts.  (dict.update()
can be updated to accept multiple dicts, but it's not out of scope).

* d = d1.merge(d2)  # d = d1.copy(); d.update(d2)
* d = d1.merge(d2, d3)  # d = d1.copy(); d.update(d2); d2.update(d3)
* d = d1.merge(iter_of_pairs)
* d = d1.merge(key=value)

## Merits of dict.merge() over operator +

* Easy to Google (e.g. "python dict merge").
* Easy to help(dict.merge). (or dict.merge? in IPython)
* No inefficiency of d1+d2+d3+...+dN, or sum(list_of_many_dicts)
* Type of returned value is always same to d1.copy().  No issubclass,
no __iadd__.

## Why not dict.updated()?

sorted() is a function so it looks different from L.sort()
But d.updated() is very similar to d.update() for human eyes.

## How about d1 - d2?

If it is really useful, it can be implemented as method too.


INADA Naoki  <songofacandy at gmail.com>

More information about the Python-ideas mailing list