[Python-ideas] Adding "+" and "+=" operators to dict
Alexander Heger
python at 2sn.net
Thu Feb 12 22:30:09 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. ... some deja-vu on the discussion ...
yes, the arguments were then as now
1) whether to use + or |, other operators that suggest asymmetric
(non-commutative) operation were suggested as well
- in my opinion dictionaries are not sets, so the use of | to indicate
set-like behaviour brings no real advantage ... + seems the most
natural for a novice and is clear enough
2) obviously, there were the same questions whether in case of key
collisions the elements should be added - i.e., apply the + operator
to the elements; it had been argued this was another reason to use |
instead of +, however, why then not apply the | operator on elements
in case of key collisions ...?
- my opinion on this is now that you just *define* - and document -
what the plus operator does for dictionaries, which should be most
naturally defined on the basis of update (for +=) and rhs elements
supersede lhs elements in a similar fashion for + as I would naively
expect. Having this kind of consistent behaviour for dictionaries
would be reasonably easy to understand and the += / + just becomes a
shorthand form for update (or the suggested updated function). This
also avoids confusion about different behaviour for different
operations - the update behaviour us how dictionaries behave - and
also limits the amount of new code that needs to be written. Operation
would be associative.
3) This would be different than the behaviour of counters, but
counters are not just plain dictionaries but have well-defined value
types for their keys so operation on items is well defined whereas
this is not the case for a dictionary in general.
I am +1 on both + and +=
-Alexander
More information about the Python-ideas
mailing list