您没有传入False 对象。您传入的是 'False' 字符串,这是一个非零长度的字符串。
只有长度为 0 的字符串测试为假:
>>> bool('')
False
>>> bool('Any other string is True')
True
>>> bool('False') # this includes the string 'False'
True
请改用store_true or store_false action。对于default=True,请使用store_false:
parser.add_argument('--bool', default=True, action='store_false', help='Bool type')
现在省略开关集args.bool 到True,使用--bool(没有进一步参数)将args.bool 设置为False:
python test.py
True
python test.py --bool
False
如果您必须解析包含True 或False 的字符串,则必须明确地这样做:
def boolean_string(s):
if s not in {'False', 'True'}:
raise ValueError('Not a valid boolean string')
return s == 'True'
并将其用作转换参数:
parser.add_argument('--bool', default=True, type=boolean_string, help='Bool type')
此时--bool False 将按照您的预期工作。