Python Glossary Русский

all Python 3numbersterm

numbers.Real

numeric tower

The abstract class of real numbers: everything from Complex plus ordering, rounding and float(). float, int and Fraction belong here.

Syntax

isinstance(x, numbers.Real)

The trap: Decimal is not Real, even though it looks like a real number. It is deliberately kept out of the tower because it does not mix with float: Decimal('1.5') + 0.5 raises TypeError. So isinstance(x, numbers.Real) rejects Decimal; if you need it, test for Number or for Decimal separately. complex is not Real either.

Examples

import numbers
from decimal import Decimal
from fractions import Fraction
print([isinstance(v, numbers.Real) for v in (2.5, 3, Fraction(1, 2), 1j, Decimal('1.5'))])  # → [True, True, True, False, False]
try:
    Decimal('1.5') + 0.5
except TypeError as e:
    print(type(e).__name__)  # → TypeError — Decimal и float не смешиваются

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy