Python Numbers Module
The numbers module defines a hierarchy of numeric abstract base classes (ABCs) which progressively define more operations. It is useful for checking if an object acts like a number, rather than checking for a specific type (like int or float).
Importing the Module
import numbers
The Numeric Hierarchy
The module defines the following hierarchy of ABCs:
Number: The root of the numeric hierarchy.Complex: Subclass ofNumber. Describes complex numbers and includes operations that work on the complex plane.Real: Subclass ofComplex. Describes real numbers (likefloat).Rational: Subclass ofReal. Describes rational numbers (likefractions.Fraction).Integral: Subclass ofRational. Describes integral numbers (likeint).
Type Checking
The primary use case for this module is to check if a number belongs to a certain category using isinstance().
Checking for Integers
If you want to accept any integer-like number (including int and potentially other custom integer types), check against numbers.Integral.
import numbers
x = 10
print(isinstance(x, numbers.Integral)) # Output: True
y = 10.5
print(isinstance(y, numbers.Integral)) # Output: False
Checking for Real Numbers
If you want to accept floating-point numbers or integers (since integers are mathematically real numbers), check against numbers.Real.
import numbers
x = 10.5
print(isinstance(x, numbers.Real)) # Output: True
y = 10
print(isinstance(y, numbers.Real)) # Output: True
Checking for Complex Numbers
numbers.Complex covers complex numbers, real numbers, and integers.
import numbers
z = 3 + 4j
print(isinstance(z, numbers.Complex)) # Output: True
Note on decimal.Decimal
It is important to note that decimal.Decimal does not inherit from numbers.Real. This is because Decimal implements decimal floating-point arithmetic, which behaves differently from binary floating-point arithmetic (represented by float and numbers.Real). Decimal inherits from numbers.Number.