ahlya / app /core /utils.py
Ba7ath-Project's picture
Add missing utility functions safe_float and safe_int
e0d6ecb
import math
from decimal import Decimal
from typing import Any
def clean_nans(obj: Any) -> Any:
"""
Recursive utility to replace NaN, Infinity, and -Infinity with None
to ensure JSON compatibility.
Standards Moez Elbey: Missing data => null/None.
"""
if isinstance(obj, float):
if math.isnan(obj) or math.isinf(obj):
return None
return obj
elif isinstance(obj, Decimal):
return float(obj)
elif isinstance(obj, dict):
return {k: clean_nans(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [clean_nans(v) for v in obj]
return obj
def safe_float(val: Any, default: float = 0.0) -> float:
"""Safely convert any value to float."""
try:
if val is None or (isinstance(val, float) and math.isnan(val)):
return default
return float(val)
except (ValueError, TypeError):
return default
def safe_int(val: Any, default: int = 0) -> int:
"""Safely convert any value to int."""
try:
if val is None or (isinstance(val, float) and math.isnan(val)):
return default
return int(float(val))
except (ValueError, TypeError):
return default
def safe_list(val: Any) -> list:
"""Ensure value is a list."""
if isinstance(val, list):
return val
return []