4

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.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Assem
  • 11,574
  • 5
  • 59
  • 97
  • Not without modifying Python itself, no (although you can do so if you wish - see e.g. http://stackoverflow.com/questions/214881/can-you-add-new-statements-to-pythons-syntax for an introduction). – jonrsharpe Sep 27 '15 at 10:10
  • @jonrsharpe: and even then, how would the number of operands by altered *at runtime*? Your only option would be to change the `~` operator meaning completely, you can't choose between 1 or 2 operands at runtime. – Martijn Pieters Sep 27 '15 at 10:12
  • @MartijnPieters that is true, you would lose the unary version – jonrsharpe Sep 27 '15 at 10:16
  • 1
    Why would you? There's a unary and a binary `+`. The choice is made at parse time. Of course you need different `__names__` for it. – Karoly Horvath Sep 27 '15 at 10:18
  • @KarolyHorvath I just heard a claim that the R's tilde operator (binary) is brought up to Python. – Assem Sep 27 '15 at 10:21

1 Answers1

11

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.

Assem
  • 11,574
  • 5
  • 59
  • 97
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343