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 -- https://mail.python.org/mailman/listinfo/python-list