我有一个函数,它可以返回以下三种情况之一:
成功(真正的)
失败(错误)
读取/解析流错误(无)
我的问题是,如果我不应该测试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"
它真的像删除== True部分一样简单吗?还是我应该添加一个tri-bool数据类型?我不希望模拟函数抛出异常,因为我希望外部程序对错误所做的只是记录它并继续。
有很多好的答案。我想再补充一点。如果您正在处理数值,而您的答案恰好是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.
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]
如果您计划修改模拟函数以包含更多返回代码,那么维护这些代码可能会成为一个问题。
模拟还可能在解析错误时引发异常,在这种情况下,您要么在这里捕获它,要么让它向上传播一级,打印位将减少为一行if-else语句。
我想强调的是,即使在某些情况下,如果expr:是不够的,因为人们想确保expr是True,而不仅仅是不同于0/None/其他,出于同样的原因,S.Lott提到了避免== None。
它确实稍微更高效,而且,锦上添花的是,它更具有人类可读性。
In [1]: %timeit (1 == 1) == True
38.1 ns ± 0.116 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [2]: %timeit (1 == 1) is True
33.7 ns ± 0.141 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)