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

Yanghao Hua yanghao.py at gmail.com
Wed May 22 08:29:20 EDT 2019


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

Problem is python do not allow you to define new operators in the
language itself, except those pre-defined you can modify their
behavior. Even in case, if python would have been able to allow me to
redefine the behavior of "=", e.g. by checking if the left hand side
has a method (e.g. __assign__) to override the default behavior of the
equal sign, I would be 100% happy already :) I have looked into all
the existing operators that python supports which looks like an
"assignment", none has been fallen in love with me. The example in
Chisel w/ Scala is: they defined quite a few operators: ":=" for
signal assignment, "<>" for bulk signal connections etc. And you can
keep inventing new operators with which your design can look really
elegant.

With Python, if people already had the thought to allow user to define
arbitrary operators, I would like to wait and contribute to that
effort. Because I think this will make Python the language of choice
for almost all future domain specific language designs. If not, with
my limited knowledge in Python internals, right now I can only
implement this "<-" "->" two arrow operators and I myself are not sure
if you guys would think it is worth a PEP and actually make it into
the language.

And this is something I have in mind for a Python DSL for HDL:

def combinational_or_sequential_logic(in: Signal, out: Signal):
    local_signal = Signal()
    local_signal <- in << 10 # read as: local_signal <- (in << 10)
    out <- local_signal + 5 # read as out <- (local_signal + 5)
    # new_signal <- 3 will raise exception, as <- does not create new object.

And the arrow operators could also be used for bulk connections of a
chain of hardware modules like this:
module_instance1 -> instance2 -> instance3->... to naturally form a
hardware pipeline ... this looks very elegant.


More information about the Python-ideas mailing list