Skip to content

Commit febbc93

Browse files
masenfclaude
andcommitted
feat: support union types in interpret_env_var_value
Instead of raising an error for union types, try each type in the union in order and return the first successful interpretation. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 7023223 commit febbc93

2 files changed

Lines changed: 21 additions & 6 deletions

File tree

reflex/environment.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,8 +243,14 @@ def interpret_env_var_value(
243243
field_type = value_inside_optional(field_type)
244244

245245
if is_union(field_type):
246-
msg = f"Union types are not supported for environment variables: {field_name}."
247-
raise ValueError(msg)
246+
errors = []
247+
for arg in (union_types := get_args(field_type)):
248+
try:
249+
return interpret_env_var_value(value, arg, field_name)
250+
except (ValueError, EnvironmentVarValueError) as e: # noqa: PERF203
251+
errors.append(e)
252+
msg = f"Could not interpret {value!r} for {field_name} as any of {union_types}: {errors}"
253+
raise EnvironmentVarValueError(msg)
248254

249255
value = value.strip()
250256

tests/units/test_environment.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -190,10 +190,19 @@ def test_interpret_enum(self):
190190
result = interpret_env_var_value("value1", _TestEnum, "TEST_FIELD")
191191
assert result == _TestEnum.VALUE1
192192

193-
def test_interpret_union_error(self):
194-
"""Test that union types raise an error."""
195-
with pytest.raises(ValueError, match="Union types are not supported"):
196-
interpret_env_var_value("test", int | str, "TEST_FIELD")
193+
def test_interpret_union_tries_each_type(self):
194+
"""Test that union types try each type in order."""
195+
# str matches first
196+
assert interpret_env_var_value("hello", int | str, "TEST_FIELD") == "hello"
197+
# int matches first
198+
assert interpret_env_var_value("42", int | str, "TEST_FIELD") == 42
199+
# bool matches before str
200+
assert interpret_env_var_value("true", bool | str, "TEST_FIELD") is True
201+
202+
def test_interpret_union_no_match(self):
203+
"""Test that union types raise an error if no type matches."""
204+
with pytest.raises(EnvironmentVarValueError, match="Could not interpret"):
205+
interpret_env_var_value("not_a_number", int | bool, "TEST_FIELD")
197206

198207
def test_interpret_unsupported_type(self):
199208
"""Test unsupported type raises an error."""

0 commit comments

Comments
 (0)