[Python-ideas] Adding "+" and "+=" operators to dict
Alexander Heger
python at 2sn.net
Fri Feb 13 21:47:17 CET 2015
>> I had started a previous thread on this, asking why there was no
>> addition defined for dictionaries, along the line of what Peter argued
>> a novice would naively expect.
> [...]
> I don't think that "novices would naively expect this" is correct, and
> even if it were, I don't think the language should be designed around
> what novices naively expect.
well, I had at least hoped this to work while not being a novice.
Because it would be nice.
> As far as I was, and still am, concerned, & is the obvious and most
> natural operator for concatenation. [1, 2]+[3, 4] should return [4, 6],
> and sum(bunch of lists) should be a meaningless operation, like
> sum(bunch of HTTP servers). Or sum(bunch of dicts).
This only works if the items *can* be added. Dics should not make
such an assumption. & is not a more natural operator, because, why
would you then not just expect that [1, 2] & [3, 4] returns [1 & 2, 3
& 4] == [0 , 0] ? the same would be true for any operator you pick.
You just define that combination of dics, + or whatever operator is
used, combines dicts using the update operation. This is how dicts
behave.
> No, that's not the argument. The argument is not that "we used the +
> operator to merge two dicts, so merging should + the values". The
> argument is that in the event of a duplicate key, adding the values
> is sometimes a common and useful thing to do.
... and sometimes it is not; in general it will fail. Replacing always works.
-Alexander
More information about the Python-ideas
mailing list