Why does argparse return None instead of [] if an append action isn't used?
Adam Funk
a24061 at ducksburg.com
Fri Jan 9 10:25:59 EST 2015
On 2015-01-09, Skip Montanaro wrote:
>> I noticed in use that if an option with the 'append' action isn't
>> used, argparse assigns None to it rather than an empty list, &
>> confirmed this interactively:
>
> I don't use argparse (or optparse), being a getopt Luddite myself, but
> can you set the default for an action in the add_argument call?
Well, duh! That works, thanks. (I can't explain why I didn't think
of that.)
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append',default=[])
_AppendAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=[], type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('--bar', action='append',default=[])
_AppendAction(option_strings=['--bar'], dest='bar', nargs=None, const=None, default=[], type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(bar=[], foo=['1', '2'])
>>> parser.parse_args('--foo 1 --bar 2'.split())
Namespace(bar=['2'], foo=['1'])
>>> parser.parse_args([])
Namespace(bar=[], foo=[])
--
Slade was the coolest band in England. They were the kind of guys
that would push your car out of a ditch. --- Alice Cooper
More information about the Python-list
mailing list