diff --git a/Lib/argparse.py b/Lib/argparse.py index d2dcfdf5682f7c..4bc275217eef82 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -1540,6 +1540,13 @@ def _get_positional_kwargs(self, dest, **kwargs): msg = _("'required' is an invalid argument for positionals") raise TypeError(msg) + # make sure 'store_true', 'store_false', or 'store_const' action + # is not specified + action = kwargs.get('action') + if action in ('store_true', 'store_false', 'store_const'): + msg = _("{action} is an invalid action for positionals", {'action': action}) + raise TypeError(msg) + # mark positional arguments as required if at least one is # always required if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]: diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 2b7f008d38564b..310d173689a53f 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -4714,6 +4714,15 @@ def test_parsers_action_missing_params(self): def test_required_positional(self): self.assertTypeError('foo', required=True) + def test_positionals_with_store_true_action(self): + self.assertTypeError('foo', action='store_true') + + def test_positionals_with_store_false_action(self): + self.assertTypeError('foo', action='store_false') + + def test_positionals_with_store_const_action(self): + self.assertTypeError('foo', action='store_const', const='bar') + def test_user_defined_action(self): class Success(Exception): diff --git a/Misc/NEWS.d/next/Library/2022-10-17-20-20-18.gh-issue-97848.RnkhKZ.rst b/Misc/NEWS.d/next/Library/2022-10-17-20-20-18.gh-issue-97848.RnkhKZ.rst new file mode 100644 index 00000000000000..de326049a6dfd6 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2022-10-17-20-20-18.gh-issue-97848.RnkhKZ.rst @@ -0,0 +1 @@ +Disallow ``store_true``, ``store_false``, and ``store_const`` actions for positional arguments in :mod:`argparse` module.