Skip to content

Commit db0b063

Browse files
authored
[Feat] replace yaml value(int/float ) from env('KEY') (#34)
1 parent 4e7c52b commit db0b063

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

primus/core/utils/yaml_utils.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,29 @@
1515
def parse_yaml(yaml_file: str):
1616
def replace_env_variables(config):
1717
"""Recursively replace environment variable placeholders in the config."""
18+
19+
def try_convert_numeric(value: str):
20+
"""Try to convert a string to int or float, else return original string."""
21+
try:
22+
if re.fullmatch(r"-?\d+", value):
23+
return int(value)
24+
return float(value) # handles 1.0, -1.5, 1e-5, etc.
25+
except ValueError:
26+
return value
27+
1828
if isinstance(config, dict):
1929
return {replace_env_variables(key): replace_env_variables(value) for key, value in config.items()}
2030
elif isinstance(config, list):
2131
return [replace_env_variables(item) for item in config]
2232
elif isinstance(config, str):
23-
return re.sub(
24-
r"\${(.*?)}",
25-
lambda m: os.environ.get(m.group(1).split(":")[0], m.group(1).split(":")[1]),
33+
pattern = re.compile(r"\${([^:{}]+)(?::([^}]*))?}")
34+
replaced = pattern.sub(
35+
lambda m: os.environ.get(m.group(1), m.group(2) or ""),
2636
config,
2737
)
38+
39+
return try_convert_numeric(replaced)
40+
2841
return config
2942

3043
with open(yaml_file, "r") as f:

0 commit comments

Comments
 (0)