Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Doc/library/operator.rst
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ The mathematical and bitwise operations are the most numerous:
.. function:: index(a)
__index__(a)

Return *a* converted to an integer. Equivalent to ``a.__index__()``.
Return *a* converted to an integer. Equivalent to ``int(type(a).__index__(a))``.

.. versionchanged:: 3.10
The result always has exact type :class:`int`. Previously, the result
Expand Down
7 changes: 5 additions & 2 deletions Lib/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,11 @@ def floordiv(a, b):
return a // b

def index(a):
"Same as a.__index__()."
return a.__index__()
"Same as int(type(a).__index__(a))."
if hasattr(type(a), '__index__'):
return int(a)
raise TypeError(f"'{type(a).__name__}' object cannot be "
"interpreted as an integer")

def inv(a):
"Same as ~a."
Expand Down
28 changes: 28 additions & 0 deletions Lib/test/test_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,34 @@ def __index__(self):
with self.assertRaises((AttributeError, TypeError)):
operator.index(None)

self.assertRaises(TypeError, operator.index)
self.assertRaises(TypeError, operator.index, 1, 1)
self.assertEqual(operator.index(True), 1)
self.assertRaises(TypeError, operator.index, '42')
self.assertRaises(TypeError, operator.index, 42.0)
x = X()
x.__index__ = lambda: 1729
self.assertEqual(operator.index(x), 1)
class F:
def __index__(self):
return 42.0
self.assertRaises(TypeError, operator.index, F())
class I(int):
def __index__():
return 42
i = I()
self.assertIs(operator.index(i), int(i))
class D:
def __index__(self):
return I(42)
with self.assertWarns(DeprecationWarning):
self.assertEqual(operator.index(D()), 42)
class S:
@staticmethod
def __index__():
return 42
self.assertEqual(operator.index(S()), 42)

def test_not_(self):
operator = self.module
class C:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Correct pure-Python version of the :func:`operator.index` to behave like the
C version. Patch by Sergey B Kirpichev.
Loading