Python __index__() Magic Method

Rate this post

Python’s __index__(self) method is called on an object to get its associated integer value. The returned integer is used in slicing or as the basis for the conversion in the built-in functions bin(), hex(), and oct(). The __index__() method is also used as a fallback for int(), float(), and complex() functions when their corresponding magic methods are not defined.

Syntax

object.__index__(self)

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Example Custom __index__()

In the following example, you create a custom class Data and overwrite the __index__() magic method so that it returns an integer 2 on a custom Data object. We then print the result of the function calls of six built-in functions that all rely on __index__().

class Data:
    def __index__(self):
        return 2


x = Data()

# All those functions may use __index__():
print(bin(x))
print(oct(x))
print(hex(x))
print(complex(x))
print(int(x))
print(float(x))

The output of those functions shows that all use the value 2 for their conversions, returned by the __index__() method:

0b10
0o2
0x2
(2+0j)
2
2.0

You can see the same output when passing the integer value 2 directly into those functions:

>>> bin(2)
'0b10'
>>> oct(2)
'0o2'
>>> hex(2)
'0x2'
>>> complex(2)
(2+0j)
>>> int(2)
2
>>> float(2)
2.0

How to Use __index__() for Slicing and Indexing

You can use the magic method __index__() on a custom class to make it possible for objects of this class to be used in a slicing or indexing operation on an iterable. Python will internally call the __index__() method to obtain the integer associated with the custom object. This integer is then used as the basis for the slicing and indexing operation.

See this example where we create a custom class My_Integer and use objects of this class as arguments for the slicing operation on a specific list my_list.

class My_Integer:
    def __init__(self, i):
        self.i = i
        
    def __index__(self):
        return self.i


x = My_Integer(1)
y = My_Integer(8)
z = My_Integer(3)

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(my_list[x])
# 2

print(my_list[y])
# 9

print(my_list[x:y:z])
# [2, 5, 8]

The objects x, y, z are of type My_Integer but they can still be used for the indexing and slicing operations as shown in the last three print statements.

How to Fix “TypeError: __index__ returned non-int (type …)”

If you override the __index__() method so that it returns a non-integer type x, Python will raise a TypeError: __index__ returned non-int (type ...x).

You can see this in the following example:

class Data:
    def __index__(self):
        return 'finxter'


x = Data()
print(int(x))

Output:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 8, in <module>
    print(int(x))
TypeError: __index__ returned non-int (type str)

To fix this error, simply return an integer value from the __index__() method like so:

class Data:
    def __index__(self):
        return 42


x = Data()
print(int(x))
# 42

References:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!