Things I have tried but did not work:
parser.add_argument('--download',type=bool,default=False)
parser.add_argument('--download',default=False,action='store_true')
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.)