8000 [3.12] gh-116850: Fix argparse for namespaces with not directly writa… · python/cpython@5464c8a · GitHub
[go: up one dir, main page]

Skip to content

Commit 5464c8a

Browse files
[3.12] gh-116850: Fix argparse for namespaces with not directly writable dict (GH-124667) (GH-124758)
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 <storchaka@gmail.com>
1 parent 7677be5 commit 5464c8a

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
@@ -1269,7 +1269,8 @@ def __call__(self, parser, namespace, values, option_string=None):
12691269
setattr(namespace, key, value)
12701270

12711271
if arg_strings:
1272-
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1272+
if not hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1273+
setattr(namespace, _UNRECOGNIZED_ARGS_ATTR, [])
12731274
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
12741275

12751276
class _ExtendAction(_AppendAction):

Lib/test/test_argparse.py

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

2304+
def test_parse_known_args_to_class_namespace(self):
2305+
class C:
2306+
pass
2307+
self.assertEqual(
2308+
self.parser.parse_known_args('0.5 1 b -w 7 -p'.split(), namespace=C),
2309+
(C, ['-p']),
2310+
)
2311+
self.assertIs(C.foo, False)
2312+
self.assertEqual(C.bar, 0.5)
2313+
self.assertEqual(C.w, 7)
2314+
self.assertEqual(C.x, 'b')
2315+
23042316
def test_parse_known_args_with_single_dash_option(self):
23052317
parser = ErrorRaisingArgumentParser()
23062318
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)
0