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

Adam Funk a24061 at ducksburg.com
Mon Jan 26 14:43:18 CET 2015


On 2015-01-09, Wolfgang Maier wrote:

> 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.

Yes, it works.


-- 
Master Foo said: "A man who mistakes secrets for knowledge is like
a man who, seeking light, hugs a candle so closely that he smothers
it and burns his hand."                            --- Eric Raymond



More information about the Python-list mailing list