Compare magnitudes
Normalize signed measurements or offsets before comparison.
Python · Function
abs() returns the absolute value of a number. Complex inputs produce their magnitude, and objects can define custom behavior with __abs__().
Call abs() with one positional argument to obtain its absolute value. Integers and floating-point values produce their non-negative magnitude, complex values produce their magnitude as a float, and custom objects can define the result through __abs__().
abs(number, /)| Name | Type | Description |
|---|---|---|
number | integer, floating-point number, complex number, or object implementing __abs__() | A number or object implementing __abs__() whose absolute value or magnitude is requested. |
The absolute value of the argument; for a complex argument, its magnitude.
abs() produces a value representing the input's absolute magnitude.__abs__().__abs__().print(abs(-42))
print(abs(3 + 4j))The first call returns 42; the second returns the complex number's magnitude, 5.0.
Normalize signed measurements or offsets before comparison.
Compute the length of a complex value in the plane.
Provide absolute-value semantics for a domain-specific numeric class.
abs() return?abs(number) returns the absolute value of a number. For a complex argument, it returns the number's magnitude.
Follow-up: What enables custom types to work with abs()? They implement __abs__(), which supplies the value returned by the call.
abs() support?The function accepts one positional argument. The documented argument may be an integer, a floating-point number, or an object implementing __abs__().
Follow-up: What happens with a complex argument? Its magnitude is returned instead of a complex result.
abs() interact with custom objects?A class can define __abs__() so that abs(instance) delegates to that method. This lets the type choose its absolute-value behavior.
Follow-up: How should a custom implementation represent its result? It should return the type's absolute-value result according to the class's numeric semantics.
__abs__()complexfloatint