Coverage for src/jquantstats/_reports/_formatting.py: 100%

16 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-06-23 06:13 +0000

1"""Shared formatting helpers for report modules.""" 

2 

3from __future__ import annotations 

4 

5import math 

6from typing import Any, TypeGuard 

7 

8 

9def _is_finite(v: Any) -> TypeGuard[int | float]: 

10 """Return True when *v* is a real, finite number.""" 

11 if not isinstance(v, (int, float)): 

12 return False 

13 return math.isfinite(float(v)) 

14 

15 

16def _fmt(value: Any, fmt: str = ".4f", suffix: str = "") -> str: 

17 """Format *value* for display; return ``"N/A"`` for non-finite values.""" 

18 if not _is_finite(value): 

19 return "N/A" 

20 return f"{float(value):{fmt}}{suffix}" 

21 

22 

23def _plotly_div(fig: Any, include_plotlyjs: bool | str = False) -> str: 

24 """Serialise a Plotly figure to a standalone HTML ``<div>``.""" 

25 import plotly.io as pio 

26 

27 return str(pio.to_html(fig, full_html=False, include_plotlyjs=include_plotlyjs)) 

28 

29 

30def _table_html(header_cells: str, body_html: str) -> str: 

31 """Wrap pre-rendered table cells and body rows in the shared report table shell.""" 

32 return ( 

33 '<table class="stats-table">' 

34 "<thead><tr>" 

35 f'<th class="metric-header">Metric</th>{header_cells}' 

36 "</tr></thead>" 

37 f"<tbody>{body_html}</tbody>" 

38 "</table>" 

39 )