You will often see developers use a special sentinel for unbounded ranges, priority queues, or shortest-path algorithms. Python makes this straightforward, but the details can trip you up when you mix in JSON, Decimal, NumPy, or sorting edge cases.
How to represent infinity in Python, both positive and negative? What are the practical differences between using float(‘inf’) and math.inf? How do I check for it, sort with it, serialize it to JSON, and work with it in Decimal or NumPy without surprises?
The canonical way to represent infinity in Python uses a special floating point value float(“inf). You can create positive and negative infinity like this:
import math
pos_inf = float('inf') # Positive infinity
neg_inf = float('-inf') # Negative infinity
also_inf = math.inf # Same as float('inf')
print(pos_inf == also_inf) # TrueCode language: PHP (php)
- Comparisons: any finite number n satisfies neg_inf < n < pos_inf.
- Arithmetic: inf + 1 is inf, but inf – inf is NaN. Always guard for NaN.
- Checks: use
math.isinf(x),math.isfinite(x),math.isnan(x).
import math
x = float('inf')
print(x > 10**30) # True
print(math.isinf(x)) # True
print(math.isfinite(x)) # False
print((x - x)) # nan
print(math.isnan(x - x)) # TrueCode language: PHP (php)
Infinity is useful when sorting values where some entries are missing or should sort to the end.
data = [3, None, 7, -2, None]
# Move None to the end by substituting +inf for the sort key
sorted_data = sorted(data, key=lambda v: v if v is not None else float('inf'))
print(sorted_data) # [-2, 3, 7, None, None]Code language: PHP (php)
If there’s no boundary, use infinity in your function parameters or algorithms.
def clamp(x, low=-float('inf'), high=float('inf')):
if x < low:
return low
if x > high:
return high
return x
print(clamp(10, high=5)) # 5
print(clamp(10)) # 10 (no bounds)Code language: PHP (php)
- Decimal: Supports infinities explicitly.
- Fraction: Does not support infinity.
from decimal import Decimal
d_inf = Decimal('Infinity')
d_ninf = Decimal('-Infinity')
print(d_inf > Decimal('1e999')) # True
# Fractions do not have an infinity representation
# Fraction(1, 0) would raise ZeroDivisionErrorCode language: PHP (php)
NumPy has numpy.inf and compatible checks.
import numpy as np
arr = np.array([1.0, np.inf, -np.inf, np.nan])
print(np.isinf(arr)) # [False True True False]
print(np.isfinite(arr)) # [ True False False False]Code language: PHP (php)
The JSON standard does not include infinity or NaN. Python’s json.dumps will emit non-standard Infinity by default, which some parsers reject. Set allow_nan=False or sanitize values.
import json, math
payload = {"max": float('inf')}
print(json.dumps(payload)) # {"max": Infinity} not strict JSON
try:
json.dumps(payload, allow_nan=False) # raises ValueError
except ValueError:
pass
def sanitize_numbers(x):
if isinstance(x, float) and (math.isinf(x) or math.isnan(x)):
return None
if isinstance(x, dict):
return {k: sanitize_numbers(v) for k, v in x.items()}
if isinstance(x, list):
return [sanitize_numbers(v) for v in x]
return x
print(json.dumps(sanitize_numbers(payload))) # {"max": null}Code language: PHP (php)
If untrusted input can flow into numeric code, block infinities and NaNs to avoid undefined math.:
def ensure_finite(x: float) -> float:
if not math.isfinite(x):
raise ValueError("Expected a finite number")
return xCode language: JavaScript (javascript)
In Python image or video pipelines, you might treat a missing upper bound as infinity and then clamp before generating delivery URLs. This avoids sending invalid values to APIs and ensures safe transforms.
import math
from cloudinary.utils import cloudinary_url
def build_limited_url(public_id: str, target_w: float):
# Treat infinity as "no limit," but hard cap to a safe maximum
MAX_W = 4096
width = MAX_W if not math.isfinite(target_w) else int(min(target_w, MAX_W))
url, _ = cloudinary_url(public_id, transformation=[{"crop": "limit", "width": width}])
return url
print(build_limited_url("sample.jpg", float('inf'))) # uses width=4096
print(build_limited_url("sample.jpg", 1200.0)) # uses width=1200Code language: PHP (php)
- Infinity in Python:
float('inf'),float('-inf'), ormath.inf. - Check with
math.isinfandmath.isfinite. Beware thatinf - infyields NaN. - JSON does not support Infinity; sanitize or replace before serialization.
- Use infinity as a clean sentinel for sorting and unbounded ranges, and clamp before generating URLs or transformations.
Build smarter media workflows with a developer-first platform. Sign up for Cloudinary free and start transforming, optimizing, and delivering your assets at scale.