[Python-ideas] Why operators are useful
songofacandy at gmail.com
Sat Mar 16 00:18:49 EDT 2019
On Sat, Mar 16, 2019 at 2:51 AM Guido van Rossum <guido at python.org> wrote:
> But I think that the folks who point out "there is already a way to do this" are missing the point that it really is easier to grasp the meaning of this:
> d = d1 + d2
> compared to this:
> d = d1.copy()
> d = d1.update(d2)
> and it is not just a matter of fewer lines of code: the first form allows us to use our visual processing to help us see the meaning quicker -- and without distracting other parts of our brain (which might already be occupied by keeping track of the meaning of d1 and d2, for example).
It seems this example is bit unfair. It is not just method vs operator,
because dict doesn't provide outer place version of update() method.
In case of set, `s = s1 | s2` can be compared to `s = s1.union(s2)`.
So dict example doesn't explain "why add operator instead of method?"
> Of course, everything comes at a price. You have to learn the operators, and you have to learn their properties when applied to different object types. (This is true in math too -- for numbers, x*y == y*x, but this property does not apply to functions or matrices; OTOH x+y == y+x applies to all, as does the associative law.)
I think behavior is more important than properties.
When we learn operator's behavior, its property is obvious.
So main point of using operator or not is consistency. Same operator
should be used for same thing as possible.
I prefer | to + because the behavior of dict.update() looks similar set.union()
rather than list.extend().
Another option I like is add + operator to not only dict, but also set.
In this case, + is used to join containers by the way most natural to the
That's what Kotlin and Scala does. (Although Scala used ++ instead of +).
Inada Naoki <songofacandy at gmail.com>
More information about the Python-ideas