1

I am confused as to when the __index__ method of a class is called. I had assumed the method would be called when ever the object was used in an indexing operation. I am not seeing __index__ called when the object is a subclass of int.

In [1]: class foo(int):
...:        def __new__(cls, value):
...:            return int.__new__(cls, value)
...:        def __index__(self):
...:            return int(self)+1

In [2]: i=foo(0)

In [3]: i
Out[3]: 0

In [4]: i.__index__()
Out[4]: 1

In [5]: [0,1,2][:i.__index__()]
Out[5]: [0]

In [6]: [0,1,2][:i]
Out[6]: []

it appears that int(i) is being used as the index not i.__index__(). What have I misunderstood?

Edited to simplify and correct the example.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Codemonkey
  • 53
  • 1
  • 7

1 Answers1

0

__index__ implements lossless conversion to int. Python only calls __index__ if it actually needs such a conversion. In your case, it doesn't need a conversion, because your i is already an int. Python just uses the int value directly.

If you want to see the code that handles this, it's under PyNumber_Index.

user2357112
  • 260,549
  • 28
  • 431
  • 505