Python __float__() Magic Method

Syntax

object.__float__(x)

The Python __float__() method implements the built-in float() function. So, when you call float(x), Python attempts to call x.__float__(). If the return value is not a float, Python will raise a TypeError. If x.__float__() is not implemented, Python attempts to call x.__index__() first 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 float()

Python’s built-in float(value) function converts the argument value to a float number. For example, float('42') converts the string value '42' into the float number 42.0.

Example Custom __float__()

In the following example, you create a custom class Data and overwrite the __float__() magic method so that it returns a float number 42.42 when trying to call float(x) on a custom Data object.

class Data:
    def __float__(self):
        return 42.42


x = Data()
res = float(x) 

print(res)
# 42.42

TypeError: float() argument must be a string or a number, not ‘…’

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

class Data:
    pass


x = Data()
res = float(x)

Output:

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

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

class Data:
    def __float__(self):
        return 42.42


x = Data()
res = float(x) 

print(res)
# 42.42

TypeError: Data.__float__ returned non-float (type …)

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

class Data:
    def __float__(self):
        return '42.42' # not a float!


x = Data()
res = float(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 = float(x)
TypeError: Data.__float__ returned non-float (type str)

The reason for the TypeError: Data.__float__ returned non-float (type ...) error is that the __float__() method must return a float value. So, to resolve the error, return a float value as shown previously:

class Data:
    def __float__(self):
        return 42.42 # This is a float!


x = Data()
res = float(x) 

print(res)
# 42.42

Fallback Method __index__() for float()

If the __float__() method is not defined on an object x on which you call float(x), Python will first attempt to call x.__index__() method to obtain a numeric value that could be automatically converted to a float.

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

class Data:
    def __index__(self):
        return 42


x = Data()
res = float(x) 

print(res)
# 42.0

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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!