Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if ArgParse optional argument is set, default value supplied

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.

Any ideas on how to execute this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading