[issue36144] Dictionary union. (PEP 584)

Brandt Bucher report at bugs.python.org
Thu Feb 27 02:04:31 EST 2020


Brandt Bucher <brandtbucher at gmail.com> added the comment:

> I think for `|=` the only choice is for it to be essentially an alias to `.update()`. So that means `cm |= other` becomes `cm.maps[0].update(other)`.

Agreed.

> These semantics make `|=` behave rather differently from `|`. Is that okay? If not, which of them should change, and how?

I don’t like this. Let me try to explain why:

So far (and to the best of my knowledge), setting and updating values on a ChainMap works exactly the same as it does for dict, with all of the same semantics (the docs themselves even say that “all of the usual dictionary methods are supported”… which now could be interpreted as meaning | and |= as well). It’s only when deleting or using the new interfaces that things get more specialized.

But that doesn’t really apply here. Having different (or worse, inconsistent) behavior for these operators, I feel, would be more confusing than helpful. Remember, a major goal of this proposal is to aid in duck typing.

So, Josh’s understanding of my intended semantics is correct, I propose that, for:

    d1 = {'a': 1, 'b': 2}
    d2 = {'b': 3, 'c': 4}
    d3 = {'a': 5, 'd': 6}
    d4 = {'d': 7, 'e': 8}
    cm1 = ChainMap(d1, d2)
    cm2 = ChainMap{d3, d4)

    cm3 = cm1 | cm2

Gives cm3 a value of:

    ChainMap(d1 | d4 | d3, d2)  # Or, equivalently: ChainMap(d1 | dict(cm2), d2)

And:

    cm1 |= cm2

Is equivalent to:

    d1 |= cm2

I don’t want to change which map is "first", and I think changing the winning behavior from that of dict will create more problems than it solves. We only need to look at how ChainMap handles the update method… it keeps the same exact behavior, rather than trying to be lazy or reversed or something.

If we *are* deciding to do something different, then I think it should have no relationship to PEP 584, which reasons out a carefully considered merge operation for dict, not ChainMap. But, it would also probably need a different operator, and be able to stand on its own merits.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue36144>
_______________________________________


More information about the Python-bugs-list mailing list