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

时间:2010-01-07 13:32:36

标签: python

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

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

我的问题是,如果我不应该对TrueFalse进行测试,我应该如何看待结果。以下是我目前的工作方式:

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"

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

6 个答案:

答案 0 :(得分:120)

if result is None:
    print "error parsing stream"
elif result:
    print "result pass"
else:
    print "result fail"

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

messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]

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

simulate也可能引发解析错误的异常,在这种情况下,你要么在这里捕获它,要么让它传播一个级别,打印位将减少为一行 - 声明。

答案 1 :(得分:107)

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

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

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

答案 2 :(得分:15)

从不,永远,永远不要说

if something == True:

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

更糟糕的是,从来没有,从不,永远不会说

if something == False:

你有not。随意使用它。

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

答案 3 :(得分:3)

我想强调一点,即使有些情况if expr :还不够,因为我们要确保exprTrue而不是0 } / None /无论如何,is首选== for the same reason S.Lott mentionned for avoiding == None

确实稍微高效一点,樱桃蛋糕更具人性化。

输入:

from time import time
t0 = time()
print ( ( 1 == 1 ) == True )
t1 = time()
print ( ( 1 == 1 ) is True )
t2 = time()
print '{:e}s\n{:e}s'.format( t1-t0, t2-t1)

输出

True
True
1.201630e-04s
8.797646e-05s

答案 4 :(得分:2)

我相信抛出异常对你的情况更好。另一种方法是返回元组的模拟方法。第一项是状态,第二项是结果:

result = simulate(open("myfile"))
if not result[0]:
  print "error parsing stream"
else:
  ret= result[1]

答案 5 :(得分:2)

有很多好的答案。我想补充一点。如果您使用数值,则错误可能会进入您的代码,而您的答案恰巧是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)}.")
Answer is not found. Answer is 0.   
Answer is: 10.   
Answer is not found. Answer is None.
### 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)}.")

Answer is: 0.
Answer is: 10.
Answer is not found. Answer is None.
相关问题