Python __int__() Magic Method

Syntax

object.__int__(x)

The Python __int__() method implements the built-in int() function. So, when you call int(x), Python attempts to call x.__int__(). If the return value is not an integer, Python will raise a TypeError. If it’s not implemented, Python attempts to call x.__index__() instead, and only if this is not implemented either, it raises a TypeError.

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.

Background int()

Python’s built-in int(value) function converts the argument value to an integer number.

For example, int('42') converts the string value '42' into the integer number 42. The int() function on a float argument rounds down to the closest integer.

Example Custom __int__()

In the following example, you create a custom class Data and overwrite the __int__() magic method so that it returns an integer number 42 when you call int(x) on a custom Data object x.

class Data:
    def __int__(self):
        return 42


x = Data()
res = int(x) 

print(res)
# 42

TypeError: int() argument must be a string, a bytes-like object or a number, not ‘…’

If you call the int(x) built-in function without defining the __int__() magic method on a given object x, Python will raise a TypeError:

class Data:
    pass


x = Data()
res = int(x) 

Output:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 6, in <module>
    res = int(x)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Data'

To fix this error, define the x.__int__() method for an object x before calling the built-in int(x) method:

class Data:
    def __int__(self):
        return 42


x = Data()
res = int(x) 

print(res)
# 42

TypeError: __int__ returned non-int (type str)

Consider the following code snippet where you try to return a string, i.e., non-integer value, in the dunder method __int__():

class Data:
    def __int__(self):
        return '42' # not an integer!


x = Data()
res = int(x) 

print(res)

Running this leads to the following error message on my computer:

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

The reason for the TypeError: __int__ returned non-int (type ...) error is that the __int__() method must return an integer value. So, to resolve the error, return an integer value as shown previously:

class Data:
    def __int__(self):
        return 42       # Integer value! :)


x = Data()
res = int(x) 

print(res)
# 42

Fallback Method __index__() for int()

If the __int__() method is not defined on an object x on which you call int(x), Python will first attempt to call x.__index__() method to obtain a numeric value associated with the object.

You can see this in the following example where you override the __index__() method by returning 42 but not the __int__() method. The int(x) method still works and returns the result of the __index__() method, i.e., 42.

class Data:
    def __index__(self):
        return 42


x = Data()
res = int(x) 

print(res)
# 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!