diff -r 2150c7d6426c Doc/library/operator.rst --- a/Doc/library/operator.rst Sat Aug 17 01:01:23 2013 +0300 +++ b/Doc/library/operator.rst Sat Aug 17 11:26:19 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 2150c7d6426c Lib/operator.py --- a/Lib/operator.py Sat Aug 17 01:01:23 2013 +0300 +++ b/Lib/operator.py Sat Aug 17 11:26:19 2013 +0300 @@ -86,8 +86,18 @@ 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) + n = index(a) + if not isinstance(n, int): + msg = ("__index__ returned non-int (type %s)" % type(n).__name__) + raise TypeError(msg) + return n def inv(a): "Same as ~a." diff -r 2150c7d6426c Lib/test/test_operator.py --- a/Lib/test/test_operator.py Sat Aug 17 01:01:23 2013 +0300 +++ b/Lib/test/test_operator.py Sat Aug 17 11:26:19 2013 +0300 @@ -170,6 +170,24 @@ 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) + class B: + def __index__(self): + return 42.0 + self.assertRaises(TypeError, operator.index, B()) + def test_indexOf(self): operator = self.module self.assertRaises(TypeError, operator.indexOf)