python - 在Python中,如果没有结果,返回什么,False还是None?

标签 python pep8

我有一个搜索查询结果的函数。如果没有结果,建议返回什么,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/

相关文章:

python - 仅使用顶点列表按比例缩放多边形

python - 自动将 python lambdas 重构为命名函数

python - 将字符串拆分为长度连续增加的子字符串 block

python - 如何根据 PEP8 格式化长 SQL 查询

python - 在不必要的 else 语句上使用 pass

python - 并行运行 CrossValidationCV

python - python google-app-engine 网站的代码覆盖率?

python - Pylint、PyChecker 还是 PyFlakes?

python - 如何防止 PyDev 的 autopep8 导入格式化程序移动 site.addsitedir() 调用?

Python 主方法位置约定