[Python-ideas] Why operators are useful

Guido van Rossum guido at python.org
Sat Mar 16 01:29:01 EDT 2019

On Fri, Mar 15, 2019 at 9:19 PM Inada Naoki <songofacandy at gmail.com> wrote:

> 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)

[Note that I made a typo in the last line. It should be `d.update(d2)`, no

> > 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.

Actually most of my post was exactly about why operators can in some cases
be better than functions (which includes methods).

> 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?"

Correct, since most of the post was already explaining it. :-)

> > 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().

That's a separate topic and I did not mean to express an opinion on it in
this post. I simply used + because it's the simplest of all operators, and
it makes it easier for everyone to follow the visual argument.

> 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
> container's type.
> That's what Kotlin and Scala does.  (Although Scala used ++ instead of +).
> ref:
> https://discuss.python.org/t/pep-584-survey-of-other-languages-operator-overload/977

This probably belongs in another thread (though IIRC it has been argued to
death already).

--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190315/446edbcf/attachment.html>

More information about the Python-ideas mailing list