[Python-ideas] PEP: Dict addition and subtraction

Inada Naoki songofacandy at gmail.com
Wed Mar 6 11:28:44 EST 2019

On Wed, Mar 6, 2019 at 10:59 PM Michael Lee <michael.lee.0x2a at gmail.com> wrote:

> I think the behavior proposed in the PEP makes sense whether you think of "+" as meaning "concatenation" or "merging".
> If your instinct is to assume "+" means "concatenation", then it would be natural to assume that {"a": 1, "b": 2} + {"c": 3, "b": 4} would be identical to {"a": 1, "b": 2, "c": 3, "b": 4} -- literally concat the key-value pairs into a new dict.

Nice explanation.  You reduced my opposite to `+` by "literally concat".
Better example, {"a": 1, "b": 2} + {"c": 4, "b": 3} == {"a": 1, "b":
2, "c": 4, "b": 3} == {"a": 1, "b": 3, "c": 4}

On the other hand, union of set is also "literally concat".  If we use
this "literally concat" metaphor,
I still think set should have `+` as alias to `|` for consistency.

> Using "|" would also violate an important existing property of unions: the invariant "d1 | d2 == d2 | d1" is no longer true. As far as I'm aware, the union operation is always taken to be commutative in math, and so I think it's important that we preserve that property in Python. At the very least, I think it's far more important to preserve commutativity of unions then it is to preserve some of the invariants I've seen proposed above, like "len(d1 + d2) == len(d1) + len(d2)".

I think both rule are "rather a coincidence than a conscious decision".

I think "|" keeps commutativity only because it's minor than `+`.  Easy operator
is abused easily more than minor operator.

And I think every "coincidence" rules are important.  They makes
understanding Python easy.
Every people "discover" rules and consistency while learning language.

This is a matter of balance.  There are no right answer.  Someone
*feel* rule A is important than B.
Someone feel opposite.

> But I do know that I'm a strong -1 on adding set operations to dicts: it's not possible to preserve the existing semantics of union (and intersection) with dict and  think expressions like "d1 | d2" and "d1 & d2" would just be confusing and misleading to encounter in the wild.

Hmm.  The PEP proposed dict - dict, which is similar to set - set (difference).
To me, {"a": 1, "b": 2} - {"b": 3} = {"a": 1} is confusing than {"a":
1, "b": 2} - {"b"} = {"a": 1}.

So I think borrow some semantics from set is good idea.
Both of `dict - set` and `dict & set` makes sense to me.

* `dict - set` can be used to remove private keys by "blacklist".
* `dict & set` can be used to choose public keys by "whiltelist".

Inada Naoki  <songofacandy at gmail.com>

More information about the Python-ideas mailing list