我有一个布尔标志,可以是
None
、True
或 False
。每个值都有不同的含义。
我理解检查
True
和 None
和 not None
的 Pythonic 方法是:
if bool_flag:
print("This will print if bool_flag is True")
# PEP8 approved method to check for True
if not bool_flag:
print("This will print if bool_flag is False or None")
# Also will print if bool_flag is an empty dict, sequence, or numeric 0
if bool_flag is None:
print("This will print if bool_flag is None")
if bool_flag is not None:
print("This will print if bool_flag is True or False")
# Also will print if bool_flag is initialized as anything except None
如果您需要检查 if 语句块中的所有三个,您可以使用梯形方法,例如:
if bool_flag:
print("This will print if bool_flag is True")
elif bool_flag is None:
print("This will print if bool_flag is None")
else:
print("This will print if bool_flag is False")
# Note this will also print in any case where flag_bool is neither True nor None
但是当标志也可以是 False
或
None
作为有效值时,just检查
True
值的 Pythonic 方法是什么?我看到了几个问题,但似乎没有达成共识。
这样写是不是“更Pythonic”:
# Option A:
if isinstance(bool_flag, bool) and not bool_flag:
print("This will print if bool_flag is False")
# Option B:
if bool_flag is not None and not bool_flag:
print("This will print if bool_flag is False")
## These two appear to be strictly prohibited by PEP8:
# Option C:
if bool_flag is False:
print("This will print if bool_flag is False")
# Option D:
if bool_flag == False:
print("This will print if bool_flag is False")
这个话题之前已经讨论过:
这似乎是可用的答案中最接近我的问题的答案(提供上面的选项 A),但即使这个答案也是含糊不清的(也建议选项 C):
然而,this答案指出
if not flag_bool
相当于if bool(flag_value) == False
,这意味着使用False
运算符检查==
等价性是检查False的官方Pythonic方法(选项D):
但这直接与这个答案相矛盾,即永远不应该使用'== False'(选项D):
当标志也可以为 None 或 True 时,选项 A 和选项 B 都是检查 False 值的有效方法。然而,在两者之间,选项B稍微简洁和直接。它显式检查标志是否不是 None,然后检查它是否为 False。这样一来,意图就更加明确了。选项 A 虽然也有效,但涉及对变量类型的额外检查,根据上下文,这可能不是必需的。
不建议使用选项 C 和 D,因为它们违反了 PEP8 指南,该指南建议仅使用
is False
来测试某个值是否实际上是单例 False 对象。如果 bool_flag 是一个可以保存其他值(例如在布尔上下文中可能评估为 False 的整数或字符串)的变量,这些选项可能不会按预期运行。