[Python-ideas] PEP: Dict addition and subtraction
zestyping at gmail.com
Thu Mar 7 12:36:46 EST 2019
On Wed, Mar 6, 2019 at 4:01 PM Chris Angelico <rosuav at gmail.com> wrote:
> On Thu, Mar 7, 2019 at 10:52 AM Josh Rosenberg
> <shadowranger+pythonideas at gmail.com> wrote:
> > Allowing dicts to get involved in + means:
> Lots of words that basically say: Stuff wouldn't be perfectly pure.
> But adding dictionaries is fundamentally *useful*. It is expressive.
It is useful. It's just that + is the wrong name.
Filtering and subtracting from dictionaries are also useful! Those are
operations we do all the time. It would be useful if & and - did these
things too—and if we have & and -, it's going to be even more obvious that
the merge operator should have been |.
Josh Rosenberg <shadowranger+pythonideas at gmail.com> wrote:
> If we were inventing programming languages in a vacuum, you could say +
> can mean "arbitrary combination operator" and it would be fine. But we're
> not in a vacuum; every major language that uses + with general purpose
> containers uses it to mean element-wise addition or concatenation, not just
If we were inventing Python from scratch, we could have decided that we
always use "+" to combine collections. Sets would combine with + and then
it would make sense that dictionaries also combine with + .
But that is not Python. Lists combine with + and sets combine with |.
Why? Because lists add (put both collections together and keep
everything), but sets merge (put both collections together and keep some).
So, Python already has a merge operator. The merge operator is "|".
For lists, += is shorthand for list.extend().
For sets, |= is shorthand for set.update().
Is dictionary merge more like extend() or more like update()? Python
already took a position on that when it was decided to name the dictionary
method update(). That ship sailed a long time ago.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas