'Argparse optional argument with different default if specified without a value

Consider three different runs of a program:

python3 prog.py
python3 prog.py --x
python3 prog.py --x 2

Is it possible to use argparse such that, for example, in the first case, x==None, in the second case, x==1, and in the third, x==2?



Solution 1:[1]

You may want to consider instead the count action, which is commonly used to specify verbosity levels. The usage is different, for example:

python3 prog.py
python3 prog.py -v
python3 prog.py -vv

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1