ZetCode

Python __float__ Method

Last modified November 17, 2026 Python 3.15

The float() built-in calls __float__ to convert an object to a floating-point number. The hook can encode a unit conversion or a domain rule, must return a real float, and has a fallback through __index__. This article shows the dispatch, return-type rules, conversions, error handling, and that fallback.

How float() calls __float__

float(obj) is evaluated as type(obj).__float__(obj). The method is looked up on the type and its result is returned unchanged. Calling the method directly gives the same result.

basic_float.py
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __float__(self):
        print("__float__ called")
        return float(self.celsius)


t = Temperature(23.5)
print(float(t))
print(type(t).__float__(t))

The message appears twice because both the built-in call and the direct call reach the hook. The printed value is the float returned by __float__.

$ python basic_float.py
__float__ called
23.5
__float__ called
23.5

The return value must be a float

Python does not coerce the result. A hook that returns an int raises TypeError, so convert with float() when the stored value is an integer.

return_type.py
class ReturnsInt:
    def __float__(self):
        return 5


class ReturnsFloat:
    def __float__(self):
        return 5.0


print(float(ReturnsFloat()))
try:
    float(ReturnsInt())
except TypeError as e:
    print(type(e).__name__, e)

Returning 5.0 works, while returning 5 raises a TypeError that names the offending type. Return a built-in float rather than a numeric string or a custom numeric object.

$ python return_type.py
5.0
TypeError ReturnsInt.__float__() must return a float, not int

Encapsulating conversions

The hook is a natural place for conversion rules. One class can turn a ratio into a decimal value, while another converts a measurement into a base unit before returning a float.

conversions.py
class Ratio:
    def __init__(self, numerator, denominator):
        self.numerator = numerator
        self.denominator = denominator

    def __float__(self):
        return self.numerator / self.denominator


class Measurement:
    def __init__(self, value, unit):
        self.value = value
        self.unit = unit

    def __float__(self):
        if self.unit == "km":
            return float(self.value * 1000)
        if self.unit == "cm":
            return float(self.value / 100)
        return float(self.value)


print(float(Ratio(1, 2)))
print(float(Ratio(1, 4)) * 100)
print(float(Measurement(5, "km")))
print(float(Measurement(150, "cm")))

The ratio is divided at conversion time, and the measurement is scaled according to its unit; unknown units fall back to the stored value. The caller simply uses float() and does not need to know the rules.

$ python conversions.py
0.5
25.0
5000.0
1.5

Rejecting an invalid conversion

When a value cannot be converted, raise an exception rather than returning a sentinel. TypeError is appropriate for an unsupported type, and ValueError for a value that is the right type but out of range.

invalid.py
class Percentage:
    def __init__(self, value):
        self.value = value

    def __float__(self):
        if isinstance(self.value, str):
            return float(self.value.rstrip("%")) / 100
        if isinstance(self.value, (int, float)):
            return float(self.value) / 100
        raise TypeError(f"cannot convert {self.value!r} to float")


print(float(Percentage("50%")))
print(float(Percentage(25)))
try:
    float(Percentage(None))
except TypeError as e:
    print(type(e).__name__, e)

A percent string and a plain number are both accepted, while None raises TypeError with a message naming the value. Keeping the error at the boundary makes failures easy to locate.

$ python invalid.py
0.5
0.25
TypeError cannot convert None to float

The __index__ fallback

If a class defines __index__ but not __float__, float() uses __index__ and converts its integer result. This is how integer-like types become floats without a dedicated hook.

index_fallback.py
class Count:
    def __init__(self, n):
        self.n = n

    def __index__(self):
        return self.n


print(float(Count(7)))
print(float(Count(3)))

Both objects yield floats through the integer returned by __index__. Defining __float__ takes priority, so add it when the conversion is not simply the integer value.

$ python index_fallback.py
7.0
3.0

Alongside other numeric methods

__float__ can coexist with operators. One method supplies a scalar view of the object, while others define how objects combine.

vector.py
import math


class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __float__(self):
        return math.hypot(self.x, self.y)

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"


v = Vector(3, 4)
print(float(v))
print(float(v + Vector(6, 8)))

The vector's magnitude is returned as a float, and adding two vectors produces a new vector whose magnitude can then be converted. Using math.hypot avoids overflow for large components.

$ python vector.py
5.0
15.0

Best practices

A conversion hook should behave like a pure function:

Source

object.__float__ - Python documentation

float() - Python documentation

Numeric types - Python documentation

In this article we have implemented the __float__ method. We have covered the float() dispatch, the return type, conversions, errors, the __index__ fallback, and numeric operators. For related topics, see Python __int__ method, Python __index__ method, and Python float() function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.