Summary
In pulseengine/core/price.py, the helper safe_pct is defined as a closure inside compute_price_metrics. While this works, PEP 8 and Python conventions prefer module-level helpers over closures when the nested function captures only one outer variable (close and latest) and is only a few lines. The current pattern:
- Makes
safe_pct impossible to test directly in isolation
- Hides a reusable utility from the module namespace
- Creates a new function object on every call to
compute_price_metrics
Location
pulseengine/core/price.py, lines 160–167 (inside compute_price_metrics):
def safe_pct(n: int) -> Optional[float]:
if len(close) > n:
old = float(close.iloc[-(n + 1)])
if abs(old) < 1e-9 or not math.isfinite(old):
return None
pct = ((latest - old) / old) * 100
return round(pct, 2) if math.isfinite(pct) else None
return None
Proposed fix
Extract to a module-level function with explicit parameters:
def _safe_pct(close: pd.Series, latest: float, n: int) -> float | None:
"""Return the n-bar percentage change relative to *latest*, or None."""
if len(close) > n:
old = float(close.iloc[-(n + 1)])
if abs(old) < 1e-9 or not math.isfinite(old):
return None
pct = ((latest - old) / old) * 100
return round(pct, 2) if math.isfinite(pct) else None
return None
This function can then be unit-tested directly in tests/test_core.py.
Summary
In
pulseengine/core/price.py, the helpersafe_pctis defined as a closure insidecompute_price_metrics. While this works, PEP 8 and Python conventions prefer module-level helpers over closures when the nested function captures only one outer variable (closeandlatest) and is only a few lines. The current pattern:safe_pctimpossible to test directly in isolationcompute_price_metricsLocation
pulseengine/core/price.py, lines 160–167 (insidecompute_price_metrics):Proposed fix
Extract to a module-level function with explicit parameters:
This function can then be unit-tested directly in
tests/test_core.py.