I'm trying to check if an optional argument is supplied by the user but I want to set its default value if it is not supplied. If I try to use if
statement by exploiting None
, the default
in help string says None
which is incorrect
import argparse
parser = argparse.ArgumentParser(usage=__file__ + " [--options]",
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--scheme", choices=["A", "B"])
parser.add_argument("--min-A", type=float, help="Default=5")
parser.add_argument("--min-B", type=float, help="Default=10")
args = parser.parse_args()
if args.scheme == "A":
if args.min_A:
min_A = args.min_A
else:
min_A = 5
else:
if args.min_A:
parser.error("--min-A can only be provided when --scheme is A")
#similar code for B
Here, the help string automatically puts default as None. If I put default as 5, then I'm not able to check whether --min-A
has been provided by user because it stores the default instead of None when the option is absent in input.
formatter_class=argparse.ArgumentDefaultsHelpFormatter
^ This custom formatter class is your problem. You can just remove it. Then your help text will render like that:
usage: myscript.py [--options]
options:
-h, --help show this help message and exit
--scheme {A,B}
--min-A MIN_A Default=5
--min-B MIN_B Default=10