From 69d12f3ce1c7e077026226511a5d0c349621e7e3 Mon Sep 17 00:00:00 2001 From: Stefan Krawczyk Date: Sun, 17 Nov 2024 00:13:46 -0800 Subject: [PATCH] Adds function to convert config types Config parser types are by default strings. They aren't converted. This adds a function to do that for ints, floats, and booleans. --- ui/sdk/src/hamilton_sdk/tracking/constants.py | 22 +++++++++++++++++++ ui/sdk/tests/tracking/test_constants.py | 21 ++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 ui/sdk/tests/tracking/test_constants.py diff --git a/ui/sdk/src/hamilton_sdk/tracking/constants.py b/ui/sdk/src/hamilton_sdk/tracking/constants.py index fc51655ed..da6f2e8cc 100644 --- a/ui/sdk/src/hamilton_sdk/tracking/constants.py +++ b/ui/sdk/src/hamilton_sdk/tracking/constants.py @@ -11,6 +11,7 @@ import configparser import logging import os +from typing import Any logger = logging.getLogger(__name__) @@ -42,12 +43,33 @@ def _load_config(config_location: str) -> configparser.ConfigParser: _constant_values = globals() file_config = _load_config(DEFAULT_CONFIG_LOCATION) + + +def _convert_to_type(val: str) -> Any: + if not isinstance(val, str): # guard + return val + if val.isdigit(): + # convert to int + val = int(val) + elif val.lower() in {"true", "false"}: + # convert to bool + val = val.lower() == "true" + else: + try: # check if float + val = float(val) + except ValueError: + pass + return val + + # loads from config file and overwrites if "SDK_CONSTANTS" in file_config: for key, val in file_config["SDK_CONSTANTS"].items(): upper_key = key.upper() if upper_key not in _constant_values: continue + # convert from string to appropriate type + val = _convert_to_type(val) # overwrite value _constant_values[upper_key] = val diff --git a/ui/sdk/tests/tracking/test_constants.py b/ui/sdk/tests/tracking/test_constants.py new file mode 100644 index 000000000..9ccab2ece --- /dev/null +++ b/ui/sdk/tests/tracking/test_constants.py @@ -0,0 +1,21 @@ +import configparser +from hamilton_sdk.tracking import constants + + +def test__convert_to_type(): + # using configparser to make it more realistic + config = configparser.ConfigParser() + config["SDK_CONSTANTS"] = { + "CAPTURE_DATA_STATISTICS": "true", + "MAX_LIST_LENGTH_CAPTURE": "5", + "MAX_DICT_LENGTH_CAPTURE": "10", + "SOMETHING_ELSE": "11.0", + "Another_thing": "1asdfasdf", + } + assert constants._convert_to_type(config["SDK_CONSTANTS"]["CAPTURE_DATA_STATISTICS"]) is True + assert constants._convert_to_type(config["SDK_CONSTANTS"]["MAX_LIST_LENGTH_CAPTURE"]) == 5 + assert constants._convert_to_type(config["SDK_CONSTANTS"]["MAX_DICT_LENGTH_CAPTURE"]) == 10 + assert constants._convert_to_type(config["SDK_CONSTANTS"]["SOMETHING_ELSE"]) == 11.0 + assert constants._convert_to_type(config["SDK_CONSTANTS"]["Another_thing"]) == "1asdfasdf" + o = object() + assert constants._convert_to_type(o) == o