This is slightly related to the topic covered in a question about allowing an argument to be specified multiple times.
I'd like to be able to specify an option multiple times like this:
tool --foo 1 --foo 2 --foo 3
And also like this:
tool a b c
I'd also like to support both at the same time:
tool a b c --foo 1 --foo2 --foo 3
This works fine with:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo', nargs='*', action='append')
parser.add_argument('--foo', nargs='*', dest='foo', action='append')
The result list can be easily flattened out:
args = parser.parse_args('a b c --foo 1 --foo 2 --foo 3'.split())
args.foo = [el for elements in args.foo for el in elements]
yields:
>>> args
Namespace(foo=['a', 'b', 'c', '1', '2', '3'])
How do I add a default value in a way that the default is not being used as soon as one argument is specified by the user?
If adding just default=[['spam']]
to one of the add_argument()
calls, the default is always part of the result. I cannot get argparse to remove it by itself as soon as a user provides an argument herself.
I'm hoping that there's a solution with what argparse
already provides itself.