Source code for lalandre_core.utils.parse_utils
"""
Generic parsing utilities.
"""
import json
from typing import Any, Dict, List, Optional, cast
# ---------------------------------------------------------------------------
# Safe type coercions (avoid scattered isinstance checks in service code)
# ---------------------------------------------------------------------------
[docs]
def as_dict(value: Any) -> Dict[str, Any]:
"""Return *value* if it is a ``dict``, else an empty ``dict``."""
if isinstance(value, dict):
return cast(Dict[str, Any], value)
return {}
[docs]
def as_optional_dict(value: Any) -> Optional[Dict[str, Any]]:
"""Return *value* if it is a ``dict``, else ``None``."""
if isinstance(value, dict):
return cast(Dict[str, Any], value)
return None
[docs]
def as_str(value: Any, *, default: str = "") -> str:
"""Coerce *value* to ``str``."""
if isinstance(value, str):
return value
if value is None:
return default
return str(value)
[docs]
def as_document_list(value: Any) -> List[Dict[str, Any]]:
"""Return only the ``dict`` items from *value* (must be a list)."""
if not isinstance(value, list):
return []
docs: List[Dict[str, Any]] = []
raw_items: List[Any] = cast(List[Any], value)
for item in raw_items:
if isinstance(item, dict):
docs.append(cast(Dict[str, Any], item))
return docs
[docs]
def to_optional_int(value: Any) -> Optional[int]:
"""Convert *value* to ``int`` when possible, else ``None``."""
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
return None
[docs]
def sanitize_error_text(error: Exception, *, max_chars: int = 220) -> str:
"""Return a truncated, safe string representation of *error*."""
text = str(error).strip() or error.__class__.__name__
return text[:max_chars]
[docs]
def coerce_bool(value: Any, default: bool) -> bool:
"""Return *value* if it is already a ``bool``, else *default*."""
if isinstance(value, bool):
return value
return default
[docs]
def coerce_float(value: Any, default: float) -> float:
"""Return *value* cast to ``float`` when it is numeric, else *default*."""
if isinstance(value, (int, float)):
return float(value)
return default