[New-bugs-announce] [issue41684] argparse: unexpected subparser behaviour on parse_args with namespace option

Lucca Ruhland report at bugs.python.org
Tue Sep 1 04:33:31 EDT 2020


New submission from Lucca Ruhland <lucca.ruhland at gmail.com>:

When parsing arguments with a namespace object, the subparser are behaving different than the main parser, although this is not stated in the documentation.

Each attribute which is not already part of the namespace, should be saved into the namespace object.
Therefore any already existing namespace attribute should overwrite the default value of any argument which is not explicitly set. 

While this is true for the parent parser, it does not work for the subparser.
Here is a small example code:
------------------------------------------------------------------------
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--root', type=str, default='.')
subparsers = parser.add_subparsers()
subparser = subparsers.add_parser('subp')
subparser.add_argument('--subroot', type=str, default='./subdir')
our_args = argparse.Namespace(root="./config_root", subroot="./config_subdir")

argv = ['subp']
args = parser.parse_args(argv, namespace=our_args)
print(args)
------------------------------------------------------------------------
>>> Expected: Namespace(root='./config_root', subroot='./config_subdir')
>>> Output: Namespace(root='./config_root', subroot='./subdir')

When calling the subparser, the namespace attribute is overwritten by the default value.

----------
assignee: docs at python
components: Documentation
messages: 376183
nosy: docs at python, lucca.ruhland
priority: normal
severity: normal
status: open
title: argparse: unexpected subparser behaviour on parse_args with namespace option
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41684>
_______________________________________


More information about the New-bugs-announce mailing list