Skip to content

Commit 685c3c4

Browse files
authored
Fix misleading error message for invalid value for Literal strings (#790)
1 parent 7b1bbcd commit 685c3c4

File tree

3 files changed

+7
-2
lines changed

3 files changed

+7
-2
lines changed

CHANGELOG.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ Fixed
2222
<https://github.com/omni-us/jsonargparse/pull/787>`__).
2323
- ``Union`` with path type and non-path value incorrectly dumped as string
2424
(`#789 <https://github.com/omni-us/jsonargparse/pull/789>`__).
25+
- Misleading error message for invalid value for ``Literal`` strings (`#790
26+
<https://github.com/omni-us/jsonargparse/pull/790>`__).
2527

2628

2729
v4.42.0 (2025-10-14)

jsonargparse/_typehints.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -781,8 +781,9 @@ def adapt_typehints(
781781
# Literal
782782
elif typehint_origin in literal_types:
783783
if val not in subtypehints and isinstance(val, str):
784-
subtypes = Union[tuple((type(v) for v in subtypehints if type(v) is not str))]
785-
val = adapt_typehints(val, subtypes, **adapt_kwargs)
784+
subtypes = tuple((type(v) for v in subtypehints if type(v) is not str))
785+
if subtypes:
786+
val = adapt_typehints(val, Union[subtypes], **adapt_kwargs)
786787
if val not in subtypehints:
787788
raise_unexpected_value(f"Expected a {typehint}", val)
788789

jsonargparse_tests/test_typehints.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,8 @@ def test_union_of_literals(parser):
183183
parser.add_argument("--literal", type=Union[Literal[1, 2], Literal["a", "b"]])
184184
assert "a" == parser.parse_args(["--literal=a"]).literal
185185
assert 2 == parser.parse_args(["--literal=2"]).literal
186+
with pytest.raises(ArgumentError, match=r"Expected a typing.Literal\['a', 'b']"):
187+
parser.parse_args(["--literal=x"])
186188

187189

188190
@parser_modes

0 commit comments

Comments
 (0)