From b6e8ef18deeb5203c2cb0d990355859f01a6eebb Mon Sep 17 00:00:00 2001 From: mcflugen Date: Mon, 29 Jan 2024 20:38:20 -0700 Subject: [PATCH 1/3] truncated float if passed as an int, issue warning --- src/model_metadata/model_parameter.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/model_metadata/model_parameter.py b/src/model_metadata/model_parameter.py index b44faf3..c3c290f 100644 --- a/src/model_metadata/model_parameter.py +++ b/src/model_metadata/model_parameter.py @@ -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" From 23543b7bc9ea723d9290d02237dec537f6146967 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Mon, 29 Jan 2024 21:33:07 -0700 Subject: [PATCH 2/3] fix converting strings to numbers in NumberParameter --- src/model_metadata/model_parameter.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/model_metadata/model_parameter.py b/src/model_metadata/model_parameter.py index c3c290f..32ed8f3 100644 --- a/src/model_metadata/model_parameter.py +++ b/src/model_metadata/model_parameter.py @@ -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) From 3871671bf6ea31d622129dc973602f57c41c986e Mon Sep 17 00:00:00 2001 From: mcflugen Date: Mon, 29 Jan 2024 21:41:44 -0700 Subject: [PATCH 3/3] add a couple int and float parameter tests --- tests/parameter_test.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 tests/parameter_test.py diff --git a/tests/parameter_test.py b/tests/parameter_test.py new file mode 100644 index 0000000..ee9ca37 --- /dev/null +++ b/tests/parameter_test.py @@ -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