Argle Argle - 2 months ago 5
Python Question

Is it possible to overload the ~ operator on strings?

>>> a = 55
>>> b = "hello"
>>> ~a # this will work
>>> ~b # this will fail


No real surprise for the failure above, but suppose I wanted to overload ~ operator to work on strings. I'm fairly new to Python, so I did some digging on this and found a few tantalizing suggestions that I just couldn't get working. I know I can create some kind of new class, but I'd like the following to work as well:

>>> ~"alpha bravo"


Is this possible? If so, how? How does one do this kind of overload?

wim wim
Answer

No, this is not possible in Python. You can not add new methods to built-in types in a way that will work reliably.

One thing you could do is subclass string, and define the magic method __invert__. But it would not work on string literals, only on instances of your subclass.

Comments