Home > database >  Cannot parse boolean values with argparse
Cannot parse boolean values with argparse

Time:02-26

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

Python version : 3.8

Why does argparse not work for boolean arguments?

CodePudding user response:

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.)

  • Related