[Python-ideas] Operator as first class citizens -- like in scala -- or yet another new operator?
yanghao.py at gmail.com
Wed May 22 05:31:29 EDT 2019
I see python3.5 accepted PEP465 adding a new infix operator for matrix
(@, @=), which made matrix formula's much less painful to read in
Python. There are still more use cases like this in other areas.
While looking at Chisel (a hardware construction language build on top
of scala), where you can create arbitrary new operators e.g. := used
for specific purposes, I realize there is no way to overload the
behavior of the assignment operator in python unless new operators are
introduced. In the python world, e.g. MyHDL (Hardware description
language in python) uses something like signal.next = 5 ... which is 5
more chars to type (.next part) for every single signal assignment,
and assign new value to a signal is the one most commonly used
operations in hardware design world.
The .next could have been saved by using python descriptors but now
you have to type something like "obj.signal = 5" instead of "signal =
5", and it does not work if you want a local signal, where signal = 5
will always make signal to be 5, instead of feeding 5 into this
I have experimented by adding two new python operators, left arrow: <-
and right arrow ->, which users can define their behaviors. and it
still looks like kind of the non-blocking assignment operators in
hardware description languages (e.g. verilog <=). Also it could be
used to build data flows like a -> b -> c -> d -> ...
Another side effect is this "__arrow__" call can fully replace
descriptors and allow you to generate descriptor-like behavior on
object initialization time instead of class definition time, e.g. in
__init__(self,...) to dynamically create self.abc like fields which
can be then accessed like obj.abc <- 3 etc. This currently with
descriptors can only be achieved elegantly by using meta classes.
This is the first time I am writing to python-ideas list, just want to
hear what you guys think, should python actually allow operators to be
first class citizens? does the arrow operator makes sense at all? Any
other better ways to redefine the "assignment" behavior by user?
More information about the Python-ideas