diff -r 1f4aed2c914c Doc/library/operator.rst --- a/Doc/library/operator.rst Sun Aug 11 20:13:36 2013 +0300 +++ b/Doc/library/operator.rst Tue Aug 13 11:55:40 2013 +0300 @@ -109,7 +109,7 @@ .. function:: index(a) __index__(a) - Return *a* converted to an integer. Equivalent to ``a.__index__()``. + Return *a* converted to an integer. Equivalent to ``type(a).__index__(a)``. .. function:: inv(obj) diff -r 1f4aed2c914c Lib/operator.py --- a/Lib/operator.py Sun Aug 11 20:13:36 2013 +0300 +++ b/Lib/operator.py Tue Aug 13 11:55:40 2013 +0300 @@ -86,8 +86,14 @@ return a // b def index(a): - "Same as a.__index__()." - return a.__index__() + "Same as type(a).__index__(a)." + try: + index = type(a).__index__ + except AttributeError: + msg = ("'%s' object cannot be interpreted as an integer" % + type(a).__name__) + raise TypeError(msg) + return index(a) def inv(a): "Same as ~a." diff -r 1f4aed2c914c Lib/test/test_operator.py --- a/Lib/test/test_operator.py Sun Aug 11 20:13:36 2013 +0300 +++ b/Lib/test/test_operator.py Tue Aug 13 11:55:40 2013 +0300 @@ -170,6 +170,20 @@ self.assertRaises(TypeError, operator.getitem, a, None) self.assertTrue(operator.getitem(a, 2) == 2) + def test_index(self): + operator = self.module + self.assertRaises(TypeError, operator.index) + self.assertRaises(TypeError, operator.index, 1, 1) + self.assertEqual(operator.index(42), 42) + self.assertRaises(TypeError, operator.index, '42') + self.assertRaises(TypeError, operator.index, 42.0) + class A: + def __index__(self): + return 42 + a = A() + a.__index__ = lambda: 1729 + self.assertEqual(operator.index(a), 42) + def test_indexOf(self): operator = self.module self.assertRaises(TypeError, operator.indexOf)