我有一个布尔(ish)标志,可以是
True
或 False
,其中 None
作为附加有效值。每个值都有不同的含义。
我理解检查
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
或
False
作为有效值时,just 检查 None
的值(当 only检查
True
时)的 Python 方式是什么?我看到了几个问题,但似乎没有达成共识。
这样写是不是“更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")
# Option E (per @CharlesDuffy):
match flag_bool:
case 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):
首先,考虑到这种数据表示对于粗心的人来说可能存在很多陷阱,可能值得考虑这是否是一个好主意。
有了这个,我认为可以安全地假设 PEP8 中对显式比较的“禁令”是为了阻止那些只对真实性真正感兴趣的初学者编写像
if (a != b) != False
这样的东西,出于某种原因,他们似乎总是在做。
如果您真的想要区分 True、False 和 None,那么使用
is
运算符显然是正确的选择。