Python __index__ Method
Last modified November 18, 2026 Python 3.15
Python calls __index__ whenever it needs an exact integer: a
list index, a slice bound, a value for range(), or the
repetition count of a sequence. Unlike __int__, the conversion
must be lossless. This article shows the protocol, every place Python uses
it, and the errors raised when a hook returns the wrong type.
operator.index and the integer contract
The operator.index(obj) function calls
type(obj).__index__(obj). The method takes no arguments beyond
self and must return an int; the print below shows
the call happening.
import operator
class Ix:
def __init__(self, value):
self.value = value
def __index__(self):
print("__index__", self.value)
return self.value
def __repr__(self):
return f"Ix({self.value})"
i = Ix(3)
print(operator.index(i))
The result is a plain int. This protocol was introduced so
that custom numeric types can be used for indexing without being silently
truncated the way int() would allow.
$ python basic_index.py __index__ 3 3
Objects as indices and slice bounds
The bracket syntax calls __index__ implicitly. Both an
ordinary index and each bound of a slice are converted, so a custom type
works in all positions without extra calls in user code.
class Ix:
def __init__(self, value):
self.value = value
def __index__(self):
print("__index__", self.value)
return self.value
xs = [10, 20, 30, 40, 50]
print(xs[Ix(3)])
print(xs[Ix(1):Ix(4)])
The single index selects 40, and the slice converts both 1 and 4 before
taking elements 20, 30 and 40. A class that only defines
__int__ would not work here: indexing requires the stricter
integer protocol.
$ python index_in_brackets.py __index__ 3 40 __index__ 1 __index__ 4 [20, 30, 40]
Everywhere Python asks for an integer
The protocol is used by several unrelated-looking operations. Building a
range, choosing a number base, repeating a sequence and rounding a float all
request an integer through __index__.
class Ix:
def __init__(self, value):
self.value = value
def __index__(self):
print("__index__", self.value)
return self.value
print(list(range(Ix(3))))
print(bin(Ix(10)), oct(Ix(9)), hex(Ix(26)))
print([0] * Ix(3))
print("ab" * Ix(2))
print(round(3.14159, Ix(2)))
Each operation makes its own call. Note that round(3.14159,
Ix(2)) passes the number of decimal places through the same protocol.
Supporting __index__ once makes an object usable in all of these
contexts.
$ python index_users.py __index__ 3 [0, 1, 2] __index__ 10 __index__ 9 __index__ 26 0b1010 0o11 0x1a __index__ 3 [0, 0, 0] __index__ 2 abab __index__ 2 3.14
__index__ versus __int__
When a class defines both methods, int(obj) uses
__int__ and operator.index(obj) uses
__index__. If __int__ is absent, both
int() and float() fall back to
__index__.
import operator
class Both:
def __init__(self, value):
self.value = value
def __index__(self):
print("__index__")
return self.value
def __int__(self):
print("__int__")
return self.value
b = Both(5)
print("int:", int(b))
print("index:", operator.index(b))
class OnlyIndex:
def __init__(self, value):
self.value = value
def __index__(self):
print("OnlyIndex.__index__")
return self.value
o = OnlyIndex(7)
print("int fallback:", int(o))
print("float fallback:", float(o))
The two hooks are chosen independently. The fallback exists because
__index__ is guaranteed to be lossless, so it is safe for
general integer conversion. Use __int__ only when the
conversion may discard information, such as rounding a float down.
$ python index_vs_int.py __int__ int: 5 __index__ index: 5 OnlyIndex.__index__ int fallback: 7 OnlyIndex.__index__ float fallback: 7.0
The return value must be an int
Returning a float is an error, with a message that names both the class
and the actual type. A bool is technically an int
subclass, but returning it is deprecated and emits a
DeprecationWarning.
import operator
import warnings
class Bad:
def __index__(self):
return 1.5
try:
operator.index(Bad())
except TypeError as e:
print(type(e).__name__, e)
class BoolIx:
def __index__(self):
return True
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
value = operator.index(BoolIx())
print(value, caught[0].category.__name__)
The float is rejected outright. The boolean is converted to 1 but warns
that returning a strict subclass of int will be removed in a
future version. Return a real int from every
__index__ implementation.
$ python bad_index.py TypeError Bad.__index__() must return an int, not float 1 DeprecationWarning
A binary index type
A custom numeric representation becomes useful once it can index a
sequence. Here a value stored as a binary string converts itself with
int(bits, 2).
import operator
class BinaryIndex:
def __init__(self, bits):
self.bits = bits
def __index__(self):
return int(self.bits, 2)
def __repr__(self):
return f"BinaryIndex({self.bits!r})"
idx = BinaryIndex("1101")
xs = [i * 10 for i in range(20)]
print(operator.index(idx))
print(xs[idx])
print(len(range(idx)))
The bits 1101 mean 13, so the index selects element 130 and
a range built from the same object contains 13 values. No conversion code is
needed at the call sites.
$ python binary_index.py 13 130 13
Enums are indexable too
The standard-library enum types IntEnum and
IntFlag implement __index__, so their members work
as indices and in bitwise expressions without extra code.
import operator
from enum import IntEnum, IntFlag
class Color(IntEnum):
RED = 1
GREEN = 2
BLUE = 3
print(operator.index(Color.GREEN))
print(["x", "red", "green"][Color.GREEN])
class Perm(IntFlag):
READ = 1
WRITE = 2
EXEC = 4
mask = Perm.READ | Perm.WRITE
print(mask, operator.index(mask), bin(mask))
Color.GREEN selects the third element because its value is 2.
Combining two flags produces a member whose integer value is 3; it can be
printed in binary just like a plain integer.
$ python enum_index.py 2 green 3 3 0b11
Best practices
A few rules keep the integer protocol predictable:
- Return a real
int; floats raiseTypeErrorandboolis deprecated. - Keep the conversion lossless — that is what distinguishes
__index__from__int__. - Implement
__index__for numeric types that should work as indices or slice bounds. - Implement
__int__separately when rounding or other lossy conversion is intended. - Expect
__index__to be called more than once in expressions with several conversions.
Source
object.__index__ - Python documentation
operator.index - Python documentation
object.__int__ - Python documentation
PEP 357 - Allowing Objects to be Indices
In this article we have implemented the __index__ method. We
have covered the integer contract, its use in indexing, slicing, ranges and
repetition, the difference from __int__, return-type errors, and
enum support. For related topics, see
Python __int__ method,
Python __float__ method, and
Python list slicing.
Author
List all Python tutorials.