我有一个搜索查询结果的函数。如果没有结果,建议返回什么,False 还是 None?
我认为这并不重要,但我想遵循最佳实践。
最佳答案
A positive result would be a short string in this case.
假设你有这样的(非常微不足道的)例子......
the_things = {'foo', 'bar'}
def find_the_thing(the_thing):
if the_thing in the_things:
return the_thing
...如果没有找到该东西,它会默认返回None
,这没关系,你可以像这样使用它...
the_thing = find_the_thing('blah')
if the_thing is not None:
do_something_with(the_thing)
else:
do_something_else()
...但有时提出这样的异常会更好...
the_things = {'foo', 'bar'}
def find_the_thing(the_thing):
if the_thing in the_things:
return the_thing
raise KeyError(the_thing)
...你可以像这样使用...
try:
do_something_with(find_the_thing('blah'))
except KeyError:
do_something_else()
...这可能更具可读性。
关于python - 在Python中,如果没有结果,返回什么,False还是None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16594103/