2

我有一个搜索查询结果的功能。如果没有结果,建议返回什么,False 还是 None?

我想这并不重要,但我想遵循最佳实践。

4

4 回答 4

3

在这种情况下,肯定的结果将是一个短字符串。

假设你有这样的(非常微不足道的)例子......

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()

...这可能更具可读性。

于 2013-05-16T18:13:05.920 回答
1

我会返回一个空列表,当你在路上查看这个函数的返回值时,它会让你头疼。

但是,如果您希望您的程序在您假设列表包含元素时终止,那么 None 是一个不错的选择。

于 2013-05-16T18:21:54.340 回答
1

我绝对不会回来FalseNone但除了vs.之外,还有其他选择False


在这种情况下,肯定的结果将是一个短字符串。

因此,否定结果可以是字符串。(当然,除非这也是一个可能的积极结果。)

正如PEP 8所说:

对于序列(字符串、列表、元组),使用空序列为假的事实。

But that's not a complete answer to your question (nor is it an iron-clad rule in the first place). You have to think through the pros and cons and decide which are most important in your actual use.


I think the biggest issue is this: If you return '', code that tries to use the result as a string will work. If you return None, that same code will raise an exception.

For example, here's a simplified version of some code I've got lying around:

result = query_function(foo, bar)
soup = bs4.BeautifulSoup(result)
for div in soup.find_all('div'):
    print(div['id'])

My query_function returns '', so the code will successfully print out no IDs. That's what I want for my script. But for a different use case, it might be better to raise an exception. In that case, I'd make query_function return None.


Or, of course, you can just make query_function itself raise an exception, as in Aya's answer.


You may want to look over the standard string methods, re methods, and other search functions in the stdlib (maybe even look at sqlite, etc.) to see what they do. (Note that in a few cases, there are matching pairs of value-returning and exception-raising functions, like str.find and str.index, so the answer might not be either one or the other, but both.)

于 2013-05-17T18:26:49.530 回答
0

不返回任何东西而是一个一个地产生结果怎么样?生成器通常是一件方便的事情,因为它们避免了构建列表,然后无论如何都会一个一个地使用和丢弃。

于 2013-05-16T19:27:52.857 回答