在Python中,我应该如何测试变量是None,True还是False

Jam*_*oks 129 python

我有一个函数可以返回三件事之一:

  • 成功(True)
  • 失败(False)
  • 错误读取/解析流(None)

我的问题是,如果我不应该反对,True或者我应该False如何看待结果.以下是我目前的做法:

result = simulate(open("myfile"))
if result == None:
    print "error parsing stream"
elif result == True: # shouldn't do this
    print "result pass"
else:
    print "result fail"
Run Code Online (Sandbox Code Playgroud)

它是否真的像删除== True部分一样简单,或者我应该添加一个tri-bool数据类型.我不希望simulate函数抛出异常,因为我希望外部程序执行错误是记录并继续.

Sil*_*ost 132

if result is None:
    print "error parsing stream"
elif result:
    print "result pass"
else:
    print "result fail"
Run Code Online (Sandbox Code Playgroud)

保持简单明了.您当然可以预先定义字典.

messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]
Run Code Online (Sandbox Code Playgroud)

如果您计划修改simulate函数以包含更多返回代码,则维护此代码可能会成为一个问题.

simulate也可能提高对解析错误的异常,在这种情况下,你要么就在这里抓住它还是让它传播水平并打印位将减少到单行if-else语句.

  • 当然,但知道这些只是可能的返回值,我认为这不是问题。 (2认同)

Pau*_*McG 112

不要害怕异常!让您的程序只需记录并继续即可轻松实现:

try:
    result = simulate(open("myfile"))
except SimulationException as sim_exc:
    print "error parsing stream", sim_exc
else:
    if result:
        print "result pass"
    else:
        print "result fail"

# execution continues from here, regardless of exception or not
Run Code Online (Sandbox Code Playgroud)

现在,您可以从模拟方法获得更丰富的通知类型,以确定出现了什么问题,以防您发现错误/无错误不足以提供足够的信息.

  • 很多人会来这个页面寻找标题问题的答案.对于我们大多数人来说"不要害怕异常!" 与我们的情况无关.我们只需要测试True,False和None.虽然您建议的替代方案对某些情况有效,但我认为最好还包括问题的答案. (8认同)
  • @Brandon不同意.这个代码比上面的解决方案(或者下面的改进版本)更长,更糟,可读性更低:更多缩进,更多不同的陈述 - 猜猜为什么后者更受欢迎,正如你所说... ;-)为什么试图成为"Pythonic"如果导致更尴尬的代码......? (6认同)

S.L*_*ott 18

永远,永远,永远不要说

if something == True:
Run Code Online (Sandbox Code Playgroud)

决不.这很疯狂,因为你冗余地重复冗余指定的if语句的冗余条件规则.

更糟糕的是,永远,永远,永远,永远不要说

if something == False:
Run Code Online (Sandbox Code Playgroud)

你有not.随意使用它.

最后,做法a == None效率低下.做a is None. None是一个特殊的单例对象,只能有一个.只需检查一下你是否有那个对象.

  • "永远,永远,永远不会......"?有些情况虽然`if something == True`会产生与`if something`不同的结果,例如对于非布尔的`something`.`2 == True`产生错误,而`2`评估为真; `None == False`是假的但是`not None`是真的! (72认同)
  • -1这个答案误导而且完全不正确,因为@Rolf Bartstra所说的是真的.虽然在这种情况下,你说*可以*应用. (7认同)
  • @Scott Griffiths:好点.这是一个真正而且非常恐怖的场景.如果确实如此,该程序违反了我们的基本期望,使其成为需要简单删除并在没有黑魔法的情况下从头开始重写的东西. (5认同)
  • 用"True"测试相等性并不是多余的(虽然我同意它不合理).它可以调用`__eq__`或其他特殊方法,它几乎可以做任何事情. (3认同)
  • -1.因为``something``的任何非零或非空或非零长度值在``bool(something)``上返回``True``.在这种情况下,如果你只想检查``something``的值是否为``True``,即``bool``.然后你必须做``if something == True`` IMO. (3认同)

Nae*_*vis 6

有很多很好的答案。我想再补充一点。如果您正在处理数值,那么错误可能会进入您的代码,而您的答案恰好是 0。

a = 0 
b = 10 
c = None

### Common approach that can cause a problem

if not a:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if not b:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}")

if not c:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")
Run Code Online (Sandbox Code Playgroud)
Answer is not found. Answer is 0.   
Answer is: 10.   
Answer is not found. Answer is None.
Run Code Online (Sandbox Code Playgroud)
### Safer approach 
if a is None:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if b is None:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}.")

if c is None:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")

Run Code Online (Sandbox Code Playgroud)
Answer is: 0.
Answer is: 10.
Answer is not found. Answer is None.
Run Code Online (Sandbox Code Playgroud)