Skip to content
Advertisement

New operators in Python

We can define intrinsic operators of Python as stated here. Just for curiosity, can we define new operators like $ or ***? (If so, then we can define ternary condition operators or rotate operators.)

Advertisement

Answer

Expanding on @fasouto answer, but adding a bit more code.

While you cannot define new operators AND you cannot redefine existing operators for built-in types, what you can do is to define a class (instantiated to any valid Python name, e.g. op) that act as an intermediate binding for two objects, thus effectively looking like a binary infix operator:

JavaScript

Non-binding Implementation

In short, one can define a class overriding forward and backward methods for an operator, e.g. __or__ and __ror__ for the | operator:

JavaScript

This can be used directly:

JavaScript

or as a decorator:

JavaScript

The above solution works as is, but there are some issues, e.g. op | 2 expression cannot be used alone:

JavaScript

Binding Implementation

To get proper bindings one would need to write a bit more complex code performing an intermediate binding:

JavaScript

This is used the same way as before, e.g. either:

JavaScript

or as a decorator:

JavaScript

With this, one would get:

JavaScript

There is also a PyPI package (with which I have no affiliation) implementing substantially this: https://pypi.org/project/infix/

Timings

Incidentally, the binding solutions seems to be also marginally faster:

JavaScript

Notes

These implementations use |, but any binary operator could be used:

  • +: __add__
  • -: __sub__
  • *: __mul__
  • /: __truediv__
  • //: __floordiv__
  • %: __mod__
  • **: __pow__
  • @: __matmul__ (for Python 3.5 onwards)
  • |: __or__
  • &: __and__
  • ^: __xor__
  • >>: __rshift__
  • <<: __lshift__

The ** would require the binding implementation or adjusting the non-binding one to reflect that the operator is right-associative. All the other operators from above are either left-associative (-, /, //, %, @, >>, <<) or directly commutative (+, *, |, &, ^).

Remember that these would all have the same precedence as the normal Python operators, hence, e.g.:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement