[Python-ideas] Operator as first class citizens -- like in scala -- or yet another new operator?

Chris Angelico rosuav at gmail.com
Wed May 22 08:12:11 EDT 2019


On Wed, May 22, 2019 at 10:03 PM Yanghao Hua <yanghao.py at gmail.com> wrote:
> > To be first-class citizens, operators would have to be able to be
> > passed to functions - for instance:
> >
> > def frob(x, y, oper):
> >     return x oper y
> > assert frob(10, 20, +) == 30
> > assert frob(10, 20, *) == 200
> >
> > The nearest Python currently has to this is the "operator" module, in
> > which you'll find function versions of the operators:
> >
> > def frob(x, y, oper):
> >     return oper(x, y)
> > assert frob(10, 20, operator.add) == 30
> > assert frob(10, 20, operator.mul) == 200
> >
> > Is this what you're talking about?
>
> Yes this is exactly what I am talking about .. and this is exactly
> what scala does.
> In scala, you can do "a + b", as well as "a.+(b)", where "+" is just a
> function of object a.
>
> You know people keep building domain specific languages for specific
> problems, and scala seems currently the only one that can truely
> enable people to build DSL elegantly. I actually do not know at all
> how to do this in CPython as I just started playing with Python
> internals a few days ago, but having an arrow operator would solve my
> immediate problem in terms of using Python to build a DSL for hardware
> design (elegantly!).
>
> Does this make sense?

Yes, it does make sense. Forgive my lack of Scala knowledge, but is it
possible for 'b' in your example to be the one that handles the
addition? Specific case:

class Seven:
    def __add__(self, other): return other + 7
    def __radd__(self, other): return 7 + other

seven = Seven()
print(seven + 1)
print(2 + seven)

This works in Python even though 2.+(seven) wouldn't know how to
handle this object. So it returns NotImplemented, and Python says, oh
okay, maybe the other object knows how to do this. (That's what
__radd__ is for.) This is why Python's operators are all defined by
the language, with multiple levels of protocol.

ChrisA


More information about the Python-ideas mailing list