Skip to content

Commit 9c18147

Browse files
authored
Union types with str and default comment-like string incorrectly parsed as a stringified exception of an other subtype (#812)
1 parent f327492 commit 9c18147

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

CHANGELOG.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ paths are considered internals and can change in minor and patch releases.
1515
v4.44.0 (unreleased)
1616
--------------------
1717

18+
Fixed
19+
^^^^^
20+
- Union types with str and default comment-like string incorrectly parsed as a
21+
stringified exception of an other subtype (`#812
22+
<https://github.com/omni-us/jsonargparse/pull/812>`__).
23+
1824
Changed
1925
^^^^^^^
2026
- Improved error messages when not accepted options are given, referencing which

jsonargparse/_typehints.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -854,7 +854,7 @@ def adapt_typehints(
854854
vals.append(ex)
855855
if all(isinstance(v, Exception) for v in vals):
856856
raise_union_unexpected_value(sorted_subtypes, val, vals)
857-
val = vals[-1]
857+
val = next((v for v in reversed(vals) if not isinstance(v, Exception)))
858858

859859
# Tuple or Set
860860
elif typehint_origin in tuple_set_origin_types:

jsonargparse_tests/test_typehints.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,12 @@ def test_str_edge_cases(parser):
125125
assert parser.parse_args([f"--val={val}"]).val == val
126126

127127

128+
def test_str_union_default_comment_like(parser):
129+
parser.add_argument("--val", type=Union[str, int], default="#default")
130+
assert "#default" == parser.get_defaults().val
131+
assert "#default" == parser.parse_args([]).val
132+
133+
128134
def test_bool_parse(parser):
129135
parser.add_argument("--val", type=bool)
130136
assert None is parser.get_defaults().val

0 commit comments

Comments
 (0)