paul j3 <ajipa...@gmail.com> added the comment:

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)

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue38843>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to