Skip to content

Commit

Permalink
Adds function to convert config types
Browse files Browse the repository at this point in the history
Config parser types are by default strings. They aren't converted.
This adds a function to do that for ints, floats, and booleans.
  • Loading branch information
skrawcz committed Nov 18, 2024
1 parent 0a4949e commit 69d12f3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
22 changes: 22 additions & 0 deletions ui/sdk/src/hamilton_sdk/tracking/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import configparser
import logging
import os
from typing import Any

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -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

Expand Down
21 changes: 21 additions & 0 deletions ui/sdk/tests/tracking/test_constants.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 69d12f3

Please sign in to comment.