Search code examples
pythonoperator-overloadingunary-operator

Is there a possibility to override a unary operator with a binary one in Python?


I tried to define a class and override the tilde operator:

class foo:
    def __invert__(self, other)
        return 1232 # a random number , just as test

Then calling it like:

>>> f = foo()
>>> g = foo()
>>> f ~ g
  File "<input>", line 1
    f ~ g
      ^
SyntaxError: invalid syntax

Can we replace the tilde operator with a binary one so we can do an operation like f ~ g without raising a syntax error.


Solution

  • No, you can't do that, not without radically altering how Python compiles bytecode. All expressions are first parsed into a Abstract Syntax Tree, then compiled into bytecode from that, and it is at the parsing stage that operands and operators are grouped.

    By the time the bytecode runs you can no longer decide to accept two operands.