Use nargs='?' to make the argument optional, const=True for when the flag is given with no argument, and default=False for when the flag is not given.
Here's the explanation and an example from the documentation on nargs='?':
'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced. Some examples to illustrate this:
>>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', nargs='?', const='c', default='d') >>> parser.add_argument('bar', nargs='?', default='d') >>> parser.parse_args(['XX', '--foo', 'YY']) Namespace(bar='XX', foo='YY') >>> parser.parse_args(['XX', '--foo']) Namespace(bar='XX', foo='c') >>> parser.parse_args([]) Namespace(bar='d', foo='d')
nargs='?'marks the argument as optional. The example given in the nargs examples[ seems to match what you're attempting to do - as soon as you clear up the confusion about example 1 & 3.nargs='?'plusdefaultandconstvalues should do the trick.