numbers ABCs Guard Numeric Inputs Without bool

Check numeric arguments with numbers.Integral and numbers.Real across int, float, and Fraction while explicitly rejecting bool subclasses of int.

PythonForm Validation

Code

pythonsnippet
24 lines
from decimal import Decimal
from fractions import Fraction
import numbers

def validate_count(value: object) -> int:
    # bool subclasses int in Python, so isinstance(True, numbers.Integral) is True
    if isinstance(value, bool) or not isinstance(value, numbers.Integral):
        raise TypeError(f"expected integer count, got {type(value).__name__}")
    if value < 0:
        raise ValueError("count must be non-negative")
    return int(value)

def is_real_scalar(value: object) -> bool:
    return isinstance(value, numbers.Real) and not isinstance(value, bool)

for sample in (5, True, 2.5, Fraction(3, 4), Decimal("1.5")):
    print(f"{sample!r:18} Real={is_real_scalar(sample)}")

print("accepted count:", validate_count(42))
for bad in (True, 1.5):
    try:
        validate_count(bad)
    except TypeError as exc:
        print("rejected:", exc)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

5                  Real=True
True               Real=False
2.5                Real=True
Fraction(3, 4)     Real=True
Decimal('1.5')     Real=False
accepted count: 42
rejected: expected integer count, got bool
rejected: expected integer count, got float

Logic trace — numbers ABCs Guard Numeric Inputs Without bool

Structurally, expect the functions validate_count and is_real_scalar and nothing else.

Iteration happens inside for sample in (5, True, 2.5, Fraction(3, 4), Decimal("1.5")) — everything outside it runs once. When the guard condition holds, TypeError and ValueError is thrown rather than a bogus value returned.

Points of care

  • Nothing requires installation; stock standard library calls fulfill the logic.
  • The guard isinstance(value, bool) or not isinstance(value, numbers.Integral) returns control immediately upon hitting an early raise when its condition holds.

Using it

The entry-point signature is def validate_count(value: object) -> int

Console traces begin each entry with — accepted count:, rejected: — when the file runs.

validate_count is what another module would consume; nothing else here is load-bearing for callers.

Key statements

def is_real_scalar(value: object) -> bool:
    return isinstance(value, numbers.Real) and not isinstance(value, bool)
except TypeError as exc:
    print("rejected:", exc)

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
The code refuses to continue: `TypeError` and `ValueError` is thrown while the state is still recoverable.
Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Every import resolves inside the standard library — `decimal`, `fractions`, `numbers`. The file defines `validate_count`, `is_real_scalar` at load time.