Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 380
Assem Avatar asked Dec 19 '22 23:12

Assem


1 Answers

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.

like image 170
Martijn Pieters Avatar answered Jan 04 '23 22:01

Martijn Pieters