Python etc / numbers (PEP-3141)

Published: 22 September 2020, 18:00

Module numbers was introduced by PEP-3141 in Python 2.6. It implements the numbers hierarchy, inspired by Scheme:

Number :> Complex :> Real :> Rational :> Integral

They are ABC classes, so they can be used in isinstance checks:

import numbers
isinstance(1, numbers.Integral)
# True

isinstance(1, numbers.Real)
# True

isinstance(1.1, numbers.Integral)
# False

In theory, Decimal should be Real but it’s not because Decimal doesn’t interoperate with float:

Decimal(1) + 1.1
# TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'

The most fun thing about numbers is that it’s not supported by mypy.