Skip to content

Commit

Permalink
✨ Added pretty_format_numerical_iterable helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
s-weigand committed Dec 29, 2022
1 parent 34c6633 commit ff93616
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
32 changes: 32 additions & 0 deletions pyglotaran_extras/inspect/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

from __future__ import annotations

from collections.abc import Generator
from collections.abc import Iterable

import numpy as np


Expand Down Expand Up @@ -81,3 +84,32 @@ def pretty_format_numerical(value: float | int, decimal_places: int = 1) -> str:
else:
format_instruction = ".0f"
return f"{value:{format_instruction}}"


def pretty_format_numerical_iterable(
input_values: Iterable[str | float], decimal_places: int | None = 3
) -> Generator[str | float, None, None]:
"""Pretty format numerical values in an iterable of numerical values or strings.
Parameters
----------
input_values: Iterable[str | float]
Values that should be formatted.
decimal_places: int | None
Number of decimal places a value should have, if None the original value will be used.
Defaults to 3
See Also
--------
pretty_format_numerical
Yields
------
str | float
Formatted string or initial value if ``decimal_places`` is None.
"""
for val in input_values:
if decimal_places is None or isinstance(val, str):
yield val
else:
yield pretty_format_numerical(val, decimal_places=decimal_places)
15 changes: 15 additions & 0 deletions tests/inspect/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
"""Tests for ``pyglotaran_extras.inspect.utils``."""
from __future__ import annotations

from collections.abc import Iterable
from textwrap import dedent

import numpy as np
import pytest

from pyglotaran_extras.inspect.utils import pretty_format_numerical
from pyglotaran_extras.inspect.utils import pretty_format_numerical_iterable
from pyglotaran_extras.inspect.utils import wrap_in_details_tag


Expand Down Expand Up @@ -144,3 +146,16 @@ def test_pretty_format_numerical(value: float, decimal_places: int, expected: st
result = pretty_format_numerical(value, decimal_places)

assert result == expected


@pytest.mark.parametrize(
"decimal_places, expected",
(
(None, ["Foo", 1, 0.009, -1.0000000000000002, np.nan, np.inf]),
(2, ["Foo", "1", "9.00e-03", "-1", "nan", "inf"]),
),
)
def test_pretty_format_numerical_iterable(decimal_places: int, expected: Iterable[str | float]):
"""Values correct formatted"""
values = ("Foo", 1, 0.009, -1.0000000000000002, np.nan, np.inf)
assert list(pretty_format_numerical_iterable(values, decimal_places)) == expected

0 comments on commit ff93616

Please sign in to comment.