Below describes the difference between default
and store_const
. Because of poor naming, this can indeed be very confusing.
There are basically two types of arguments Python supports:
Argument with value
Example: --seed 42
You cannot omit the value part even if you set default as shown below:
parser = argparse.ArgumentParser()
parser.add_argument('--seed', default=42)
parser.parse_args('--seed 20'.split()) # seed is now 20
parser.parse_args(''.split()) # seed is now 42
parser.parse_args('--seed'.split()) # ERROR, must supply argument value
Argument without value
Example: --no-cuda
Here you cannot supply value to the argument, either argument exist or it doesn't. The action = "store_const"
means that the argument value is whatever is set in the const
parameter when the argument is present. If argument is not present then it takes the value specified in the default
parameter.
parser = argparse.ArgumentParser()
parser.add_argument('--use-cuda', action='store_const', const=False, default=True)
parser.parse_args('--use-cuda'.split()) # use-cuda is now False
parser.parse_args(''.split()) # use-cuda is now True
parser.parse_args('--use-cuda True'.split()) # ERROR: unrecognized arguments: True
Using const
without default
Now what if you did not specify default
? Well, in that case, default
just assumes the value of None
as shown below:
parser = argparse.ArgumentParser()
parser.add_argument('--use-cuda', action='store_const', const=False)
parser.parse_args('--use-cuda'.split()) # use-cuda is now False
parser.parse_args(''.split()) # use-cuda is now None
parser.parse_args('--use-cuda True'.split()) # ERROR: unrecognized arguments: True
Shortcut for boolean arguments
Now you can see that the value of const
and default
are usually opposite for the boolean arguments. To make this convenient, Python has shortcut actions called store_true
and store_false
. The store_true
is same as const=True
and default=False
. The store_false
other way around.