我有一个函数可以返回三件事之一:
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语句.
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)
现在,您可以从模拟方法获得更丰富的通知类型,以确定出现了什么问题,以防您发现错误/无错误不足以提供足够的信息.
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是一个特殊的单例对象,只能有一个.只需检查一下你是否有那个对象.
有很多很好的答案。我想再补充一点。如果您正在处理数值,那么错误可能会进入您的代码,而您的答案恰好是 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)