ZetCode

Python __abs__ Method

Last modified November 17, 2026 Python 3.15

The built-in abs() function returns the absolute value of a number. For an object, Python does not calculate that value itself: it looks up the object's __abs__ method and calls it. This article shows how the method is found, how to implement it for custom classes, and what happens when the method is missing or returns something unexpected.

How abs() works

For a built-in number, abs() is handled by the numeric type itself. Integers, floats, Decimal, Fraction, and complex numbers all define __abs__, but they do not all return the same type. For int, float, Decimal, and Fraction, the result keeps the type of the operand. A complex number produces a float magnitude, and a bool produces an int.

builtin_abs.py
from decimal import Decimal
from fractions import Fraction

values = [-5, -2.5, -0.0, 3 + 4j, Decimal('-1.25'), Fraction(-3, 4), True]

for value in values:
    print(f"{value!r:>20} -> {abs(value)!r}")

Negative zero becomes positive zero, and abs(True) is the integer 1 because bool is a subclass of int. The Decimal and Fraction results keep their original types, while (3+4j) produces the float 5.0. In every case, Python called the type's __abs__ method.

$ python builtin_abs.py
                  -5 -> 5
                -2.5 -> 2.5
                -0.0 -> 0.0
              (3+4j) -> 5.0
    Decimal('-1.25') -> Decimal('1.25')
     Fraction(-3, 4) -> Fraction(3, 4)
                True -> 1

Implementing __abs__ for a custom type

A custom numeric type can define __abs__ to return a new instance of the same class. The method receives only self; the value that abs() returns is whatever the method returns. The following Distance class keeps its unit and its sign handling in one place.

distance_abs.py
class Distance:
    def __init__(self, meters):
        self.meters = meters

    def __abs__(self):
        return Distance(abs(self.meters))

    def __repr__(self):
        return f"Distance({self.meters} m)"

d = Distance(-12.5)
print(abs(d))
print(type(abs(d)).__name__)
print(d)

The original d is unchanged, and abs(d) returns a new Distance object. This is the usual convention for immutable value types: an operation produces a new value instead of modifying the receiver. The special method is looked up on the type, not on the instance.

$ python distance_abs.py
Distance(12.5 m)
Distance
Distance(-12.5 m)

Returning a magnitude

For a vector, the absolute value usually means its length. The method can compute a derived value rather than return an attribute, so abs() becomes a natural way to ask for the magnitude. The example also uses abs as a sort key.

vector_abs.py
import math


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

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

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


vectors = [Vector(3, 4), Vector(-5, 12), Vector(0, 0)]
for vector in vectors:
    print(f"{vector} -> {abs(vector)}")

print(sorted(vectors, key=abs))

math.hypot computes the Euclidean norm without overflowing for large components, which is safer than writing (x**2 + y**2) ** 0.5 by hand. Sorting with key=abs orders the vectors by length, from the zero vector to the longest one.

$ python vector_abs.py
Vector(3, 4) -> 5.0
Vector(-5, 12) -> 13.0
Vector(0, 0) -> 0.0
[Vector(0, 0), Vector(3, 4), Vector(-5, 12)]

The return value is not checked

The data model says that __abs__ should return the absolute value, but CPython does not verify the type of the result. A method that returns a string simply makes abs() return that string. The same is true for NotImplemented: unlike arithmetic operators, abs() does not treat it as a request to try another operation.

abs_return.py
class Label:
    def __abs__(self):
        return "not a number"


class NoAbs:
    pass


print(abs(Label()))

try:
    abs(NoAbs())
except TypeError as e:
    print(type(e).__name__, e)

class Incomplete:
    def __abs__(self):
        return NotImplemented

print(abs(Incomplete()))

Returning a non-number breaks the contract of abs() and will surprise callers, even though the call itself succeeds. An object with no __abs__ at all raises TypeError; the message names the type that could not be handled. Do not return NotImplemented from __abs__: there is no reflected fallback for the unary abs() operation.

$ python abs_return.py
not a number
TypeError bad operand type for abs(): 'NoAbs'
NotImplemented

operator.abs and math.fabs

operator.abs is the function form of the built-in and follows the same protocol. math.fabs is different: it converts its argument to a float and returns a float, so it uses __float__ rather than __abs__. A class can therefore support one of these calls without supporting the other.

operator_abs.py
import math
import operator


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

    def __abs__(self):
        return Temperature(abs(self.celsius))

    def __float__(self):
        return float(self.celsius)

    def __repr__(self):
        return f"Temperature({self.celsius} °C)"


class OnlyFloat:
    def __float__(self):
        return -3.5


t = Temperature(-7)
print(operator.abs(t))
print(math.fabs(t))
print(type(operator.abs(t)).__name__)
print(type(math.fabs(t)).__name__)

print(math.fabs(OnlyFloat()))
try:
    print(abs(OnlyFloat()))
except TypeError as e:
    print(type(e).__name__, e)

For Temperature, both calls happen to produce the same numeric value, but they return different types: operator.abs returns a Temperature, while math.fabs returns a float. OnlyFloat has no __abs__, so abs() raises TypeError, yet math.fabs() works through __float__.

$ python operator_abs.py
Temperature(7 °C)
7.0
Temperature
float
3.5
TypeError bad operand type for abs(): 'OnlyFloat'

Best practices

An __abs__ implementation should be predictable and should not change the object. The following rules keep it consistent with the rest of the numeric protocol:

Source

abs - Python documentation

object.__abs__ - Python documentation

operator.abs - Python documentation

math.fabs - Python documentation

In this article we have implemented and used the __abs__ method. We have seen how abs() dispatches to the method, how a custom type can return a new value or a magnitude, and how operator.abs differs from math.fabs. For related topics, see Python abs built-in, Python __neg__ method, Python __int__ method, Python __float__ method, and Python operators.

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.