[issue43192] Argparse complains argument required when default is provided

paul j3 report at bugs.python.org
Tue May 4 17:13:34 EDT 2021


paul j3 <ajipanca at gmail.com> added the comment:

To a large degree the Action parameters operate independently.  That is, different parts of the code use the parameters for their own purposes. The composite behavior is a result of those individual actors, rather than some sort of overall coordinated plan.

First your Action is 'positional' (no flag string), and "store" type.  nargs is the default None.  The only extra is the default value (the default default is None).

_ActionsContainer._get_positional_kwargs processes such an argument, setting the 'required' parameter with:

        # mark positional arguments as required if at least one is
        # always required
        if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
            kwargs['required'] = True
        if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
            kwargs['required'] = True

At the start of parsing, all 'default' values are added to the 'args' Namespace.

If an Action is "seen", either via the appropriate flag string, or a positional value, it is added to the "seen_actions" list.

At the end of parsing, it iterates through all the '_actions'.  If it is not in the 'seen_actions' list, and is marked "required", it gets added to the 'reqiuired_action' error list.

So even though your Action has a 'default' it is still required.  The default is, in effect, ignored.  The nargs value (default or not) has priority in setting the 'required' value.

'?/*' nargs require special handling.  This nargs requirement is satisfied by an empty list.  Such a positional will, in effect, always be seen. But if a explicit default is provided, that will over write the empty list. 

Handling defaults is inherently tricky.  But except for the special '?/*' case, specifying a 'default' with a positional doesn't make much sense.

----------
nosy: +paul.j3

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


More information about the Python-bugs-list mailing list