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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With