Check finite numeric input before processing
Also published in our Blogger archive.
Check finite numeric input before processing
A parsed floating-point value can be finite, infinity, or NaN. Before using a measurement in arithmetic that assumes an ordinary real number, test it with math.isfinite. This avoids accepting special values merely because they have Python's float type.
The helper accepts a finite distance and doubles it. For 12.5, the processed result is 25.0. It rejects both float("nan") and positive infinity by raising ValueError; the example verifies those paths with a small assertion helper. The output is deterministic because it prints only the accepted calculation.
math.isfinite(x) returns true only when x is neither infinity nor NaN. It is available from Python 3.2 onward. This check is not complete input validation: it does not parse text, enforce a domain range such as nonnegative distance, or decide whether integers, Decimal values, or custom numeric classes should be accepted. Add those rules explicitly where the meaning of the input requires them. It also does not prove that the result of every later operation will remain finite; operations can overflow or otherwise produce a non-finite result, so check results too when that matters.
The exact behavior, including that zero is finite, is described in the official math.isfinite documentation.
AI assistance disclosure: This article was drafted with AI assistance and should be integrated with application-specific parsing and range checks.
import math
def doubled_distance(value):
if not math.isfinite(value):
raise ValueError("distance must be finite")
return value * 2
def raises_value_error(value):
try:
doubled_distance(value)
except ValueError:
return True
return False
assert doubled_distance(12.5) == 25.0
assert raises_value_error(float("nan"))
assert raises_value_error(float("inf"))
print(f"doubled={doubled_distance(12.5):.1f}")
doubled=25.0