Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Truncate floats when passed to IntParameter #30

Merged
merged 4 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions src/model_metadata/model_parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,13 +238,13 @@ def __init__(
if range_ is not None and len(range_) != 2:
raise ValueError("range must be either None or (min, max)")

try:
value = int(value)
except ValueError:
value = float(value)
finally:
if not isinstance(value, (int, float)):
raise ValueError("value is not a number")
if isinstance(value, str):
try:
value = int(value)
except ValueError:
value = float(value)
if not isinstance(value, (int, float)):
raise ValueError("value is not a number")

super().__init__(value, desc=desc)

Expand Down Expand Up @@ -382,6 +382,14 @@ def __init__(
range: tuple[int, int] | None = None,
units: str | None = None,
):
if isinstance(value, float):
warnings.warn(
f"{value}: floating point number passed as an integer parameter, value"
f" will be truncated to {int(value)}",
stacklevel=2,
)
value = int(value)

if not isinstance(value, (int, str)):
raise ValueError(
"value must be either an int or a string that can be converted to"
Expand Down
19 changes: 19 additions & 0 deletions tests/parameter_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from __future__ import annotations

import pytest
from model_metadata.model_parameter import FloatParameter
from model_metadata.model_parameter import IntParameter


@pytest.mark.parametrize("value", (1973, 1973.0, 1973.5, "1973"))
def test_int_parameter(value):
p = IntParameter(value)
assert isinstance(p.value, int)
assert p.value == 1973


@pytest.mark.parametrize("value", (3.14, "3.14"))
def test_float_parameter(value):
p = FloatParameter(value)
assert isinstance(p.value, float)
assert p.value == 3.14