当变量也可以是 None 或 True 时检查 False

问题描述 投票:0回答:1

我有一个布尔(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")


这个话题之前已经讨论过:

  1. 检查False的正确方法是什么?
  2. 在Python中我应该如何测试变量是None、True还是False
  3. 检查空字符串时“== False”和“is not”有区别吗?
  4. 为什么使用“==”或“is”比较字符串有时会产生不同的结果?
  5. “==”和“is”有区别吗?

这似乎是可用的答案中最接近我的问题的答案(提供上面的选项 A),但即使这个答案也是含糊不清的(也建议选项 C):

  1. https://stackoverflow.com/a/37104262/22396214

然而,this答案指出

if not flag_bool
相当于
if bool(flag_value) == False
,这意味着使用
False
运算符检查
==
等价性是检查
False
的官方Pythonic方法(选项D) :

  1. https://stackoverflow.com/a/36936790/22396214

但这直接与这个答案相矛盾,即永远不应该使用

== False
(选项D):

  1. https://stackoverflow.com/a/2021257/22396214
python boolean nonetype boolean-expression truthy
1个回答
0
投票

首先,考虑到这种数据表示对于粗心的人来说可能存在很多陷阱,可能值得考虑这是否是一个好主意。

有了这个,我认为可以安全地假设 PEP8 中对显式比较的“禁令”是为了阻止那些只对真实性真正感兴趣的初学者编写像

if (a != b) != False
这样的东西,出于某种原因,他们似乎总是在做。

如果您真的想要区分 True、False 和 None,那么使用

is
运算符显然是正确的选择。

© www.soinside.com 2019 - 2024. All rights reserved.