From d396422d9f6f3ba36d04fcbd454ac831e1197ea7 Mon Sep 17 00:00:00 2001 From: Mauricio Villegas <5780272+mauvilsa@users.noreply.github.com> Date: Fri, 21 Nov 2025 07:01:01 -0500 Subject: [PATCH] Union types with str and default comment-like string incorrectly parsed as a stringified exception of an other subtype --- CHANGELOG.rst | 6 ++++++ jsonargparse/_typehints.py | 2 +- jsonargparse_tests/test_typehints.py | 6 ++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 3b2bd8ba..c2eaeb7f 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -15,6 +15,12 @@ paths are considered internals and can change in minor and patch releases. v4.44.0 (unreleased) -------------------- +Fixed +^^^^^ +- Union types with str and default comment-like string incorrectly parsed as a + stringified exception of an other subtype (`#812 + `__). + Changed ^^^^^^^ - Improved error messages when not accepted options are given, referencing which diff --git a/jsonargparse/_typehints.py b/jsonargparse/_typehints.py index 43b82b73..d429d210 100644 --- a/jsonargparse/_typehints.py +++ b/jsonargparse/_typehints.py @@ -854,7 +854,7 @@ def adapt_typehints( vals.append(ex) if all(isinstance(v, Exception) for v in vals): raise_union_unexpected_value(sorted_subtypes, val, vals) - val = vals[-1] + val = next((v for v in reversed(vals) if not isinstance(v, Exception))) # Tuple or Set elif typehint_origin in tuple_set_origin_types: diff --git a/jsonargparse_tests/test_typehints.py b/jsonargparse_tests/test_typehints.py index 0c0445b5..2dc0bee4 100644 --- a/jsonargparse_tests/test_typehints.py +++ b/jsonargparse_tests/test_typehints.py @@ -125,6 +125,12 @@ def test_str_edge_cases(parser): assert parser.parse_args([f"--val={val}"]).val == val +def test_str_union_default_comment_like(parser): + parser.add_argument("--val", type=Union[str, int], default="#default") + assert "#default" == parser.get_defaults().val + assert "#default" == parser.parse_args([]).val + + def test_bool_parse(parser): parser.add_argument("--val", type=bool) assert None is parser.get_defaults().val