What is `operator.__inv__` existing for?

Viewed 496

What is the difference with inv and invert?

>>> import operator
>>> operator.inv is operator.invert
False
>>> operator.__inv__ is operator.__invert__
False

I gather that __invert__ is the hook for the unary ops like ~1 or (1).__invert__().

But what is the other one __inv__ corresponding to? Or if it's same, why we have another name and a different function added for doing same thing?

1 Answers

Both represent the same operator. The long spelling was added in Python 2.0, and the short spelling was never removed.

operator.inv(obj)

operator.invert(obj)

operator.__inv__(obj)

operator.__invert__(obj)

Return the bitwise inverse of the number obj. This is equivalent to ~obj.

New in version 2.0: The names invert() and __invert__().

Source: Python 2 operator documentation.

These are implemented as different objects because their representation reflects the name. Note that the corresponding dunder and regular names do share the same representation and object.

>>> operator.__inv__
<built-in function inv>
>>> operator.__invert__
<built-in function invert>
>>> operator.__inv__ is operator.inv
True
>>> operator.__invert__ is operator.invert
True

Historically, both names were equally viable - the Python 1 operator module used the inv/__inv__ name, whereas the Python 1 data model used the special method __invert__ name.

Related