我有一个函数,它可以返回以下三种情况之一:
成功(真正的)
失败(错误)
读取/解析流错误(无)
我的问题是,如果我不应该测试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.
不要害怕异常!让你的程序只记录并继续,就像这样简单:
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
现在,您可以从模拟方法获得更丰富的通知类型,以确定究竟是什么出错了,以防您发现错误/无错误信息不够丰富。
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语句。