gh-116850: Fix argparse for namespaces with not directly writable dict (GH-124667)

It now always uses setattr() instead of setting the dict item to modify
the namespace. This allows to use a class as a namespace.
This commit is contained in:
Serhiy Storchaka 2024-09-29 11:01:10 +03:00 committed by GitHub
parent f1a2417b9e
commit 95e92ef6c7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 16 additions and 1 deletions

View File

@ -1224,7 +1224,8 @@ class _SubParsersAction(Action):
setattr(namespace, key, value)
if arg_strings:
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
if not hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
setattr(namespace, _UNRECOGNIZED_ARGS_ATTR, [])
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
class _ExtendAction(_AppendAction):

View File

@ -2344,6 +2344,18 @@ class TestAddSubparsers(TestCase):
(NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']),
)
def test_parse_known_args_to_class_namespace(self):
class C:
pass
self.assertEqual(
self.parser.parse_known_args('0.5 1 b -w 7 -p'.split(), namespace=C),
(C, ['-p']),
)
self.assertIs(C.foo, False)
self.assertEqual(C.bar, 0.5)
self.assertEqual(C.w, 7)
self.assertEqual(C.x, 'b')
def test_parse_known_args_with_single_dash_option(self):
parser = ErrorRaisingArgumentParser()
parser.add_argument('-k', '--known', action='count', default=0)

View File

@ -0,0 +1,2 @@
Fix :mod:`argparse` for namespaces with not directly writable dict (e.g.
classes).