diff --git a/Lib/argparse.py b/Lib/argparse.py index d24fa72e573d4f..51c43a3f07a99d 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -2237,11 +2237,16 @@ def consume_positionals(start_index): # twice (which may fail) if the argument was given, but # only if it was defined already in the namespace if (action.default is not None and - isinstance(action.default, str) and hasattr(namespace, action.dest) and action.default is getattr(namespace, action.dest)): - setattr(namespace, action.dest, + if isinstance(action.default, str): + setattr(namespace, action.dest, self._get_value(action, action.default)) + elif (action.nargs not in (OPTIONAL, None) and + isinstance(action.default, (list, tuple)) and + all(isinstance(v, str) for v in action.default)): + setattr(namespace, action.dest, + [self._get_value(action, v) for v in action.default]) if required_actions: raise ArgumentError(None, _('the following arguments are required: %s') % diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 488a3a4ed20fac..394c78ab14726c 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -607,6 +607,25 @@ class TestOptionalsNargsDefault(ParserTestCase): ('-x a', NS(x='a')), ] +class TestNargsDefaultConvert(ParserTestCase): + """Tests not specifying the number of args for an Optional""" + + argument_signatures = [Sig('-x', type=int, nargs='+', default=['1', '2'])] + failures = [] + successes = [ + ('', NS(x=[1, 2])), + ] + + +class TestListDefaultConvert(ParserTestCase): + """Tests not specifying the number of args for an Optional""" + + argument_signatures = [Sig('-x', type=int, default=['1', '2'])] + failures = [] + successes = [ + ('', NS(x=['1', '2'])), + ] + class TestOptionalsNargs1(ParserTestCase): """Tests specifying 1 arg for an Optional""" diff --git a/Misc/NEWS.d/next/Library/2025-04-19-12-15-54.gh-issue-132717.TJQ9_b.rst b/Misc/NEWS.d/next/Library/2025-04-19-12-15-54.gh-issue-132717.TJQ9_b.rst new file mode 100644 index 00000000000000..949fcb9d7119c8 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-04-19-12-15-54.gh-issue-132717.TJQ9_b.rst @@ -0,0 +1,2 @@ +:mod:`argparse` now calls the convert function for default values in variadic +arguments. Patch by Noam Cohen.