Why does argparse return None instead of [] if an append action isn't used?

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Fri Jan 9 16:50:07 CET 2015


On 01/09/2015 03:44 PM, Adam Funk 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:
>
> #v+
>>>> import argparse
>>>> parser = argparse.ArgumentParser()
>>>> parser.add_argument('--foo', action='append')
> _AppendAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>>> parser.add_argument('--bar', action='append')
> _AppendAction(option_strings=['--bar'], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>>> parser.parse_args('--foo 1 --foo 2'.split())
> Namespace(bar=None, foo=['1', '2'])
> #v-
>

Isn't that the exact behaviour documented here:

https://docs.python.org/3/library/argparse.html#default

where it says that the default for the default argument is None ?

I think Skip is right: you should be able to just add

default = []

to your arguments in the add_argument call.

Wolfgang




More information about the Python-list mailing list