Skip to content

Commit 11d4b54

Browse files
[3.13] gh-116850: Fix argparse for namespaces with not directly writable dict (GH-124667) (GH-124757)
It now always uses setattr() instead of setting the dict item to modify the namespace. This allows to use a class as a namespace. (cherry picked from commit 95e92ef) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 597b621 commit 11d4b54

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Lib/argparse.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1252,7 +1252,8 @@ def __call__(self, parser, namespace, values, option_string=None):
12521252
setattr(namespace, key, value)
12531253

12541254
if arg_strings:
1255-
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1255+
if not hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1256+
setattr(namespace, _UNRECOGNIZED_ARGS_ATTR, [])
12561257
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
12571258

12581259
class _ExtendAction(_AppendAction):

Lib/test/test_argparse.py

+12
Original file line numberDiff line numberDiff line change
@@ -2365,6 +2365,18 @@ def test_parse_known_args(self):
23652365
(NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']),
23662366
)
23672367

2368+
def test_parse_known_args_to_class_namespace(self):
2369+
class C:
2370+
pass
2371+
self.assertEqual(
2372+
self.parser.parse_known_args('0.5 1 b -w 7 -p'.split(), namespace=C),
2373+
(C, ['-p']),
2374+
)
2375+
self.assertIs(C.foo, False)
2376+
self.assertEqual(C.bar, 0.5)
2377+
self.assertEqual(C.w, 7)
2378+
self.assertEqual(C.x, 'b')
2379+
23682380
def test_parse_known_args_with_single_dash_option(self):
23692381
parser = ErrorRaisingArgumentParser()
23702382
parser.add_argument('-k', '--known', action='count', default=0)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :mod:`argparse` for namespaces with not directly writable dict (e.g.
2+
classes).

0 commit comments

Comments
 (0)