[Python-ideas] PEP: Dict addition and subtraction

MRAB python at mrabarnett.plus.com
Thu Mar 21 23:31:46 EDT 2019


On 2019-03-22 02:40, Dan Sommers wrote:
> On 3/21/19 9:19 PM, Christopher Barker wrote:
>>>
>>> https://docs.python.org/3.8/library/collections.html has some
>>> examples using collections.Counter, which is clearly described
>>> as being a subclass of dict.  Amongst the examples:
>>>
>>>      c + d  # add two counters together:  c[x] + d[x]
>>>
>>> That's the + operator operating on two dicts (don't make me
>>> quote the Liskov Substitution Principle), but doing something
>>> really different than the base operator.
>>>
>>> So if I know that c and d (or worse, that one of them) is a
>>> dict, then interpreting c + d becomes much more interesting,
>> 
>> 
>> Killing a use of a common operator with a very common built in data type
>> because the operator is used in a different way by a specialized object in
>> the stdlib seems a bit backwards to me.
> 
> Perhaps.  Note that Counter also uses | and & for other
> operations that probably wouldn't make much sense on base
> dicts.
> 
>> Frankly, I think considering Counter as a dict subclass is the mistake
>> here, even if it is true.
> 
> I had the same thought that Counter is misdesigned in one
> way or another, but (a) that ship has long sailed, and (b)
> I didn't want to run off on that tangent.
> 
[snip]
Counter is trying to provide the functionality of 2 kinds of container:

1. A counting container.

2. A multi-set.

+ makes sense for counting (sum); | makes sense for multi-sets (union).


More information about the Python-ideas mailing list