Python argparse: default value or specified value
argparse, default-value, python
Solution
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)
% test.py
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)
- `nargs='?'` means 0-or-1 arguments
- `const=1` sets the default when there are 0 arguments
- `type=int` converts the argument to int
If you want `test.py` to set `example` to 1 even if no `--example` is specified, then include `default=1`. That is, with
parser.add_argument('--example', nargs='?', const=1, type=int, default=1)
then
% test.py
Namespace(example=1)
Problem
I would like to have a optional argument that will default to a value if only the flag is present with no value specified, but store a user-specified value instead of the default if the user specifies a value. Is there already an action available for this? An example: ``` python script.py --example # args.example would equal a default value of 1 python script.py --example 2 # args.example would equal a default value of 2 ``` I can create an action, but wanted to see if there was an existing way to do this.