[Python-ideas] PEP: Dict addition and subtraction

Dan Sommers 2QdxY4RzWzUUiLuE at potatochowder.com
Thu Mar 21 22:40:52 EDT 2019


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.

My point remains:  because Counter is a subclass of dict,
and Counter uses the + operator for something that doesn't
apply to base dicts, adding + to dicts *may* cause
confusion that wasn't there before.

Presently, +, -, |, and & all raise an exception when given
a Counter and a dict.  This (raising an exception) is
probably still the Right Thing to do in that case, even with
a + operator on dicts, but that violates the LSP and IMO the
PLS.


More information about the Python-ideas mailing list