[issue16878] argparse: positional args with nargs='*' defaults to []
paul j3
report at bugs.python.org
Wed Apr 17 09:11:51 CEST 2013
paul j3 added the comment:
In this example:
>>> p.add_argument('--foo', nargs='*', default=None)
>>> p.parse_args([])
Namespace(foo=None)
>>> p.parse_args(['--foo'])
Namespace(foo=[])
'p.parse_args([])' just assigns the default to 'foo' in the Namespace.
"p.parse_args(['--foo'])" invokes 'take_action(<dest='foo'>,[]). That is, it 'assigns' an empty array to 'foo'. The same thing would happen if 'foo' was a positional.
'take_action' then passes these arguments to '_get_values'. That is where the differences between '?' and '*' arise.
The key pieces of code in '_get_values' when arg_strings==[] are:
# optional argument produces a default when not present
if not arg_strings and action.nargs == OPTIONAL:
....value = action.default
# and evaluate 'value' if is a string
# when nargs='*' on a positional, if there were no command-line
# args, use the default if it is anything other than None
elif (not arg_strings and action.nargs == ZERO_OR_MORE ...):
if action.default is not None:
value = action.default
else:
value = arg_strings # i.e. []
In other words, if nargs='?', the attribute gets its default value. But for '*', this is true only if the default is not None.
So in:
parse([], nargs='?') # get the default value: None
parse([], nargs='*') # default is None, get arg_strings []
parse([], nargs='*', default=None) # same case
parse([], nargs='*', default=False) # default is not None, get default
parse([], nargs='*', default=0) # same case
I tried changing the _get_values() so '*' got the default (like '?' does), and got 54 failures when running test_argparse.py.
----------
nosy: +paul.j3
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16878>
_______________________________________
More information about the Python-bugs-list
mailing list