[Python-ideas] Why operators are useful
raymond.hettinger at gmail.com
Fri Mar 15 14:54:03 EDT 2019
> On Mar 15, 2019, at 10:51 AM, Guido van Rossum <guido at python.org> wrote:
> The general idea here is that once you've learned this simple notation, equations written using them are easier to *manipulate* than equations written using functional notation -- it is as if our brains grasp the operators using different brain machinery, and this is more efficient.
There is no question that sometimes operators can be easier to manipulate and reason about than equivalent methods. The use of "+" and "*" are a major win for numeric and sequence types.
There is also no question that sometimes method names are better than operators (otherwise, we wouldn't use method names at all). APL is an extreme example of a rich set of operators being both powerful and opaque.
So, we have to ask whether we're stretching too far from "operators are good" to "we need this operator". Here are some considerations:
Frequency of usage: Math provides ∑ and ∏ because they are common. It doesn't provide a special operator for sqrt(c**2 - b**2) because the latter is less fundamental and less common. To me, f=d.copy() followed by f.update(e) arises so rarely that an operator isn't warranted. The existing code is already concise, clear, and rare.
Familiarity: We know about + because we use it a lot in addition and concatenation contexts. However, a symbol like ⊗ is more opaque unless we're using it every day for a particular purpose. To me, the "+" operator implies "add/extend" semantics rather than "replace" semantics. Successive applications of "+" are never idempotent unless one operand is an identity element. So for me, "+" isn't familiar for dict merges. Loosely put, it isn't "plus-like". I think this is why so many other languages decided not use "+" for dict merges even when that would have been a trivially easy implementation choice.
Obviousness: When working with "+" on numeric types, it is obvious it should be commutative. When using "+" when sequence types, it is obvious that concatenation is non-commutative. When using "+" for mapping types, it is not obvious that it isn't commutative. Likewise, it isn't obvious that "+" is a destructive operation for mappings (consider that adding to a log file never destroys existing log entries, while updating a dict will overwrite existing values).
Harmony: The operators on dict views use "|" but regular dicts would use "+". That doesn't seem harmonious.
Impact: When a class in the standard library adds a method or operator, the reverberations are felt only locally. In contrast, the dict API is fundamental. Changing it will reverberate for years. It will be felt in the ABCs, typeshed, and every mapping-like object. IMO such an impactful change should only be made if it adds significant new functionality rather than providing a slightly shorter spelling of something we already have.
More information about the Python-ideas