This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author paul.j3
Recipients docs@python, paul.j3, rhettinger, zerkms
Date 2019-11-19.04:34:57
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1574138099.68.0.0906992799388.issue38843@roundup.psfhosted.org>
In-reply-to
Content
It doesn't have to be a special class. It can be a `argparse.Namespace` object.  If the preexisting namespace has an attribute set, the action default will not over write it.

    In [85]: parser = argparse.ArgumentParser() 
        ...: parser.add_argument('--foo', default='bar') 
        ...: parser.parse_args([],
                 namespace=argparse.Namespace(foo=123, baz=132))   
    Out[85]: Namespace(baz=132, foo=123)

This is described in comments at the start of parse_known_args()

        ....
        # add any action defaults that aren't present
        for action in self._actions:
            if action.dest is not SUPPRESS:
                if not hasattr(namespace, action.dest):
                    if action.default is not SUPPRESS:
                        setattr(namespace, action.dest, action.default)

        # add any parser defaults that aren't present
        for dest in self._defaults:
            if not hasattr(namespace, dest):
                setattr(namespace, dest, self._defaults[dest])

There are many details about 'defaults' that are not documented.  This might not be the most significant omission.  

I have not seen many questions about the use of a preexisting namespace object (here or on StackOverflow).  While such a namespace can be used to set custom defaults (as shown here), I think it is more useful when using a custom Namespace class, one the defines special behavior.

Originally the main parser's namespace was passed to subparsers.  But a change in 2014, gave the subparser a fresh namespace, and then copied values from it back to the main namespace.  While that gave more power to the subparser's defaults, users lost some ability to use their own namespace class.

https://bugs.python.org/issue27859 - argparse - subparsers does not retain namespace

https://bugs.python.org/issue9351 - argparse set_defaults on subcommands should override top level set_defaults

https://bugs.python.org/issue34827 - Make argparse.NameSpace iterable (closed)
History
Date User Action Args
2019-11-19 04:34:59paul.j3setrecipients: + paul.j3, rhettinger, docs@python, zerkms
2019-11-19 04:34:59paul.j3setmessageid: <1574138099.68.0.0906992799388.issue38843@roundup.psfhosted.org>
2019-11-19 04:34:59paul.j3linkissue38843 messages
2019-11-19 04:34:57paul.j3create