Python __invert__ Method
Last modified November 18, 2026 Python 3.15
The unary ~ operator calls __invert__ on its
operand. For integers it means bitwise NOT, which is equivalent to
-(x + 1). This article shows that behaviour, how a fixed-width
mask keeps complements inside a chosen number of bits, and two documented
cases where the operator is repurposed for a different domain.
Basic bitwise inversion
A class implements __invert__ to define what ~obj
means. The method takes no arguments beyond self, and the usual
convention for a non-mutating operation is to return a new instance.
class BitwiseNumber:
def __init__(self, value):
self.value = value
def __invert__(self):
print("__invert__")
return BitwiseNumber(~self.value)
def __repr__(self):
return f"BitwiseNumber({self.value})"
num = BitwiseNumber(5)
print(~num)
The hook delegating to ~self.value gives -6 for
the value 5. The original object is untouched; the operator returns the new
BitwiseNumber that the hook created.
$ python basic_invert.py __invert__ BitwiseNumber(-6)
The ~x == -(x + 1) identity
Python integers have an unlimited number of leading sign bits. Inverting
all of them means ~x is always -(x + 1), including
for negative inputs. This identity is often easier to reason about than the
phrase "flip all the bits".
for x in (0, 5, -7):
print(x, ~x, -(x + 1), ~x == -(x + 1))
Inverting zero gives -1, inverting 5 gives -6, and inverting -7 gives 6. The last column confirms the identity for all three cases. A fixed-width complement must apply a mask precisely because Python does not use a fixed width for integers.
$ python invert_identity.py 0 -1 -1 True 5 -6 -6 True -7 6 6 True
A fixed-width bit pattern
To get the familiar complement of, say, a four-bit value, mask the result
with (1 << width) - 1. The mask keeps the answer in the
chosen number of bits instead of producing a negative Python integer.
class Bits:
def __init__(self, value, width=8):
self.value = value
self.width = width
self.mask = (1 << width) - 1
def __invert__(self):
return Bits((~self.value) & self.mask, self.width)
def __repr__(self):
return f"Bits({self.value:0{self.width}b}, width={self.width})"
b = Bits(0b0011, 4)
print(b)
print(~b)
print((~b).value)
The four-bit pattern 0011 becomes 1100, whose
integer value is 12. Without the mask ~3 would be -4, which is
not the intended complement of a four-bit field.
$ python fixed_width.py Bits(0011, width=4) Bits(1100, width=4) 12
Complementing a set of flags
Flags are a natural use for a fixed-width complement: inverting a
permission mask should list the permissions that are absent. The
__or__ method lets us build a combined mask first.
class Flag:
def __init__(self, value):
self.value = value
def __invert__(self):
return Flag(~self.value & 0b111)
def __or__(self, other):
return Flag(self.value | other.value)
def __repr__(self):
return f"Flag({format(self.value, '03b')})"
READ = Flag(0b001)
WRITE = Flag(0b010)
EXEC = Flag(0b100)
permissions = READ | WRITE
print(permissions, ~permissions)
Read and write together are 011; the complement is
100, meaning "execute only". The mask 0b111 is
what makes this a three-flag complement rather than a negative integer.
$ python flag_complement.py Flag(011) Flag(100)
Double inversion
Because each inversion creates a new object, applying ~
twice restores the value but not the identity. This is the same convention
as other non-mutating operators.
class Bits:
def __init__(self, value, width=4):
self.value = value
self.mask = (1 << width) - 1
def __invert__(self):
return Bits((~self.value) & self.mask)
def __repr__(self):
return f"Bits({self.value:04b})"
b = Bits(0b0011)
print(b, ~~b, b is ~~b)
The value is back to 0011, but b is ~~b is
False because two new objects were created along the way. If
inversion were meant to mutate, the hook would return self
instead — but that would be surprising for a unary operator.
$ python double_invert.py Bits(0011) Bits(0011) False
Matrix inversion as a documented extension
Python lets you assign any meaning you like to an operator, so
~ can stand for a matrix inverse if the class documents it. The
example uses the closed-form inverse of a 2×2 matrix and rejects a singular
one.
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __invert__(self):
(a, b), (c, d) = self.rows
det = a * d - b * c
if det == 0:
raise ValueError("matrix is singular")
return Matrix([[d / det, -b / det],
[-c / det, a / det]])
def __repr__(self):
return f"Matrix({self.rows})"
print(~Matrix([[4, 7], [2, 6]]))
try:
~Matrix([[1, 2], [2, 4]])
except ValueError as e:
print(type(e).__name__, e)
The determinant is 10, so the inverse has entries 0.6, -0.7, -0.2 and
0.4. The second matrix has determinant zero and is rejected. This use of
~ is unconventional, so it needs a clear docstring for anyone
reading the code.
$ python matrix_invert.py Matrix([[0.6, -0.7], [-0.2, 0.4]]) ValueError matrix is singular
Logical inversion of a role
A second documented extension is logical negation: a role whose flags are
the opposite of another role's. This is useful in access-control tests, but
it should be spelled out because ~ normally means bitwise NOT.
class Role:
def __init__(self, read, write, execute):
self.read = read
self.write = write
self.execute = execute
def __invert__(self):
return Role(not self.read,
not self.write,
not self.execute)
def __repr__(self):
return (f"Role(read={self.read}, "
f"write={self.write}, execute={self.execute})")
admin = Role(True, True, True)
print(~admin)
print(~~Role(False, False, False))
Inverting a role with all permissions gives one with none. Applying
~ twice to the empty role returns to the empty role, because
the two negations cancel out. The hook uses not, so it produces
real booleans rather than bitwise integers.
$ python role_invert.py Role(read=False, write=False, execute=False) Role(read=False, write=False, execute=False)
The operator.invert function
operator.invert(x) is the functional form of ~x.
It calls the same hook and is handy when a function is needed, for example
as an argument to map().
import operator
class Bits:
def __init__(self, value, width=4):
self.value = value
self.mask = (1 << width) - 1
def __invert__(self):
return Bits((~self.value) & self.mask)
def __repr__(self):
return f"Bits({self.value:04b})"
print(operator.invert(Bits(0b0011)))
print(operator.invert(5))
The custom object uses its masked hook, while the plain integer uses the built-in bitwise NOT and gives -6. Both go through the same protocol; only the types differ.
$ python operator_invert.py Bits(1100) -6
Best practices
A few rules keep unary inversion predictable:
- Return a new object for a value-like type; mutate
selfonly if you explicitly document it. - Mask the result when you want a fixed-width complement; Python integers are not fixed width.
- Remember
~x == -(x + 1)for plain integers, including negative ones. - Check for a zero determinant before returning a matrix inverse.
- Document any meaning of
~that is not bitwise NOT.
Source
object.__invert__ - Python documentation
Unary operations - Python documentation
operator.invert - Python documentation
In this article we have implemented the __invert__ method. We
have covered bitwise NOT, the integer identity, fixed-width masks, flag
complements, double inversion, and documented non-bitwise uses. For related
topics, see Python __and__ method,
Python __or__ method, and
Python bitwise operators.
Author
List all Python tutorials.