
Steven D'Aprano wrote:
On Sun, Oct 20, 2019 at 11:29:54PM -0000, Dominik Vilsmeier wrote:
The question is, why would someone who has experience with adding counters but never felt the need to add dicts, assume that this behavior is specialized in Counter and not inherited by dict. I think you might mean inherited from dict? dict doesn't inherit Counter's behaviour because Counter is the subclass and dict the parent class.
Yes, sorry for the confusion, I meant "inherited from". One of the occasional non-native speaker issues :-)
Maybe at some point they'll encounter a scenario where they need to recursive-merge (the Counter style) two dicts and then they might assume that they just need to add the dicts Okay. So what? If they do this, it will be a mistake. Programmers make mistakes thousands of times a day, it is neither our responsibility nor within our power to prevent them all. Programmer error is not a good reason to reject a feature.
But it is the responsibility to assists programmers and help them make as few errors as possible by providing a clear and unambiguous syntax. If a specific syntax feature is ambiguous in its meaning, it's more likely to be an attractor of errors.
since they're familiar with this behavior from Counter and Counter subclasses dict so it's reasonable to assume this behavior is inherited. No it isn't reasonable. Counters are designed to count. Their values are supposed to be ints, usually positive ints. dicts are general key:value stores where the values can be any kind of object at all, not just numbers or even strings. Most objects don't support addition. It is totally unreasonable to assume that dict addition will add values by default when by default, objects cannot be added.
I fully agree to that. But someone working with dicts which store floats or lists might be tempted to assume that `d1 + d2` means "add the values" (especially if they're reading the code). If in that specific context it's perfectly fine (and maybe even reasonable) to add dict values it is more difficult to neglect that assumption (unless they're already familiar with the syntax). Yes, it's the programmers responsibility to be aware of what specific syntax does, but the language should assist as much as possible.
how obvious is the conclusion that dict performs a shallow merge and resolves conflicting keys by giving precedence to the r.h.s. operand? About as obvious that update performs a shallow merge and resolves duplicate keys by giving precedence to the last seen value.
Only if you know that "+" means "update" in that specific context. Otherwise one could even think that there are already ways to copy-merge two dicts, so why would they introduce new syntax for that, so "+" must be meaning something else (possibly the complementary, preserving l.h.s. values).