2 min read

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:

  1. Number: The root of the numeric hierarchy.
  2. Complex: Subclass of Number. Describes complex numbers and includes operations that work on the complex plane.
  3. Real: Subclass of Complex. Describes real numbers (like float).
  4. Rational: Subclass of Real. Describes rational numbers (like fractions.Fraction).
  5. Integral: Subclass of Rational. Describes integral numbers (like int).

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.

programming/python/python