Skip to content

Commit

Permalink
Add ability to convert iterables.
Browse files Browse the repository at this point in the history
  • Loading branch information
nealkruis committed Dec 12, 2023
1 parent 84e87c5 commit ab0456d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
16 changes: 11 additions & 5 deletions koozie/koozie.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,19 +69,25 @@ def convert_q(value: float, from_units: str, to_units: str) -> pint.Quantity:


# Public functions
def fr_u(value: float, from_units: str):
def fr_u(value: float | Iterable, from_units: str) -> float | List[float]:
"""Convert a value from given units to base SI units"""
return fr_q(value, from_units).magnitude
if isinstance(value, float):
return fr_q(value, from_units).magnitude
return [fr_q(v, from_units).magnitude for v in value]


def to_u(value: float, to_units: str) -> float:
"""Convert a value from base SI units to any other units"""
return to_q(value, to_units).magnitude
if isinstance(value, float):
return to_q(value, to_units).magnitude
return [to_q(v, to_units).magnitude for v in value]


def convert(value: float, from_units: str, to_units: str):
def convert(value: float, from_units: str, to_units: str) -> float:
"""Convert a value from any units to another units of the same dimension"""
return convert_q(value, from_units, to_units).magnitude
if isinstance(value, float):
return convert_q(value, from_units, to_units).magnitude
return [convert_q(v, from_units, to_units).magnitude for v in value]


def get_dimensionality(units: str) -> pint.util.UnitsContainer:
Expand Down
14 changes: 14 additions & 0 deletions test/test_koozie.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ def test_units():
assert fr_u(3.41241633, "Btu/h") == approx(1.0, 0.0001)


def test_dimensionality():
"""Test dimensionality"""
assert get_dimensionality("°F") == get_dimensionality("°C")
assert get_dimensionality("kW") == get_dimensionality("(lb_m*inch*meter)/(minute^2*day)")
assert get_dimensionality("F") != get_dimensionality("C")


def test_iterable():
"""Test converting iterable"""
temperatures = fr_u([5, 17, 35, 47, 82, 95], "°F")
assert isinstance(temperatures, list)
assert len(temperatures) == 6


runner = CliRunner()


Expand Down

0 comments on commit ab0456d

Please sign in to comment.