You are not passing in the False
object. You are passing in the 'False'
string, and that's a string of non-zero length.
Only a string of length 0 tests as false:
>>> bool('')
False
>>> bool('Any other string is True')
True
>>> bool('False') # this includes the string 'False'
True
Use a store_true
or store_false
action instead. For default=True
, use store_false
:
parser.add_argument('--bool', default=True, action='store_false', help='Bool type')
Now omitting the switch sets args.bool
to True
, using --bool
(with no further argument) sets args.bool
to False
:
python test.py
True
python test.py --bool
False
If you must parse a string with True
or False
in it, you'll have to do so explicitly:
def boolean_string(s):
if s not in {'False', 'True'}:
raise ValueError('Not a valid boolean string')
return s == 'True'
and use that as the conversion argument:
parser.add_argument('--bool', default=True, type=boolean_string, help='Bool type')
at which point --bool False
will work as you expect it to.