On this page
  1. numbers
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Writing Numeric Helpers That Reject Booleans Cleanly
  7. Gotchas & Boundaries
  8. Classes & Objects

numbers

Prev: nturl2path | Up: stdlib_module | Next: opcode
Rel: math, cmath, decimal, fractions, random
Ref: docs.python.org — numbers
Tags: #public #python3 #stdlib


Import

import numbers

Overview

Abstract numeric tower (Number > Complex > Real > Rational > Integral) defining mathematical interfaces rather than concrete types. Use isinstance(x, numbers.Real) or numbers.Integral when writing generic math utilities that should accept built-ins, Fraction, Decimal (note caveat below), or NumPy numeric scalars.

Quick Start

import numbers
from fractions import Fraction

assert isinstance(42, numbers.Integral)
assert isinstance(Fraction(1, 3), numbers.Rational)
assert isinstance(3.14, numbers.Real)
assert isinstance(1 + 2j, numbers.Complex)
assert not isinstance(1 + 2j, numbers.Real)

Implementation Walkthrough

1. Writing Numeric Helpers That Reject Booleans Cleanly

Because bool is a subclass of int, isinstance(True, numbers.Real) is True—exclude bool explicitly when validating numeric inputs:

import numbers

def ensure_real(value: object) -> float:
    if isinstance(value, bool) or not isinstance(value, numbers.Real):
        raise TypeError(f"Expected real number, got {type(value).__name__}")
    return float(value)

assert ensure_real(3) == 3.0

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes