[Python-ideas] PEP: Dict addition and subtraction

Dan Sommers 2QdxY4RzWzUUiLuE at potatochowder.com
Thu Mar 21 20:21:50 EDT 2019


On 3/21/19 6:46 PM, Steven D'Aprano wrote:

> Antoine and Serhiy seem to worry that there are existing uses of + which
> are currently easy to understand but will become less so if dict.__add__
> is added. I respect that worry, even if I doubt that they are correct.
> 
> If someone can demonstrate that their fear is well-founded, that would
> be an excellent counter-argument to the PEP's proposal to use +.

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,
but arguably no worse than c.update(d).  Yes, it's "just"
polymorphism, but IMO it violates the Principle of Least
Surprise.

My apologies if this is covered elsewhere in this thread, or
it doesn't meet the bar Steven set.


More information about the Python-ideas mailing list