Python __invert__() Magic Method

Syntax

object.__invert__(self)

The Python __invert__() method implements the unary arithmetic operation bitwise NOT ~. So, when you cal ~x, Python will internally call x.__invert__() to obtain the inverted object. If the method is not implemented, Python will raise a TypeError.

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Background Bitwise NOT ~

Python’s bitwise NOT operator ~x inverts each bit from the binary representation of integer x so that 0 becomes 1 and 1 becomes 0. This is semantically the same as calculating ~x == -x-1. For example, the bitwise NOT expression ~0 becomes -1, ~9 becomes -10, and ~32 becomes -33.

Example Custom __invert__()

In the following minimal example, you create a custom class Data and overwrite the __invert__() magic method so that it returns a dummy string when trying to calculate the bitwise NOT operation.

class Data:
        
    def __invert__(self):
        return 'finxter'


x = Data()
print(~x)
# finxter

If you hadn’t defined the __invert__() method, Python would’ve raised a TypeError.

TypeError: bad operand type for unary ~: ‘…’

Consider the following code snippet where you try to calculate the bitwise NOT operation on custom objects without defining the dunder method __invert__():

class Data:
    pass


x = Data()
print(~x)

Running this leads to the following error message on my computer:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 7, in <module>
    print(~x)
TypeError: bad operand type for unary ~: 'Data'

The reason for this error is that the __invert__() method has never been defined—and it is not defined for a custom object by default. So, to resolve the TypeError: bad operand type for unary ~, you need to provide the __invert__(self) method in your class definition as shown previously:

class Data:
        
    def __invert__(self):
        return 'finxter'


x = Data()
print(~x)
# finxter

References:

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!