Skip to content

Commit 95e92ef

Browse files
pythongh-116850: Fix argparse for namespaces with not directly writable dict (pythonGH-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.
1 parent f1a2417 commit 95e92ef

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Lib/argparse.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1224,7 +1224,8 @@ def __call__(self, parser, namespace, values, option_string=None):
12241224
setattr(namespace, key, value)
12251225

12261226
if arg_strings:
1227-
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1227+
if not hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1228+
setattr(namespace, _UNRECOGNIZED_ARGS_ATTR, [])
12281229
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
12291230

12301231
class _ExtendAction(_AppendAction):

Lib/test/test_argparse.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2344,6 +2344,18 @@ def test_parse_known_args(self):
23442344
(NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']),
23452345
)
23462346

2347+
def test_parse_known_args_to_class_namespace(self):
2348+
class C:
2349+
pass
2350+
self.assertEqual(
2351+
self.parser.parse_known_args('0.5 1 b -w 7 -p'.split(), namespace=C),
2352+
(C, ['-p']),
2353+
)
2354+
self.assertIs(C.foo, False)
2355+
self.assertEqual(C.bar, 0.5)
2356+
self.assertEqual(C.w, 7)
2357+
self.assertEqual(C.x, 'b')
2358+
23472359
def test_parse_known_args_with_single_dash_option(self):
23482360
parser = ErrorRaisingArgumentParser()
23492361
parser.add_argument('-k', '--known', action='count', default=0)
Lines changed: 2 additions & 0 deletions
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)