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

Cannot parse boolean values with argparse

Things I have tried but did not work:

  1. parser.add_argument('--download',type=bool,default=False)
  2. parser.add_argument('--download',default=False,action='store_true')
  3. parser.add_argument('--download',action='store_true')

For case 1, Passing False also gets interpreted as True.
For case 2 and 3, I get the error

main.py: error: unrecognized arguments: False

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

Python version : 3.8

Why does argparse not work for boolean arguments?

>Solution :

The way ‘store_true’ works is that if you give --download as an argument, then the value is true; and if you omit it, it is false.

The reason type=bool doesn’t work as you want is that any nonempty string passed to the bool function will result in True. (You could, if you wanted, write a function that returns True if the string is "True" and False if it is "False", and use that for type, but that is not the typical use-case.)

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