re.findall() return None 可以吗?

Can re.findall() return None?

documentation只能说是returns"a list"。我假设当它找不到匹配项时,它 returns 是一个空列表(但不是 None)并且它永远不会 returns 一个 None。但我不确定。谁能确认一下?

此外,有没有办法让我在未来自行检查其他功能(例如 ElementTree.findall())?我可以假设只要文档说 "a list" 它就会以相同的方式运行吗?

>>> import re
>>> s = "hello"
>>> re.findall("a", s)
[]

对于这类问题,打开你的 python shell 和 运行 它:根据文档,它总是 return 一个列表,但什么也没有查找,所以它是一个空列表。

内心问题:

"I just want the documentation to say "it doesn't return None" or "it always returns a list"."

我认为您需要了解 Python 文档的风格。第一行是

"Return all non-overlapping matches of pattern in string, as a list of strings".

如果它 return 编辑了其他内容,它会说明这一点。例如:在同一页上,对于子:

"Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged"

这说明了边缘情况

您不能假设任何人任何库中编写的所有函数将拥有与 python 核心一样好的文档。但是对于 Python 中的核心功能,是的,它们通常几乎总是按照文档所说的那样做。 (核心功能是以下子页面内的任何内容:https://docs.python.org/2/contents.html or https://docs.python.org/3/contents.html

如果您从 pypi 中随机获取一个库,文档可能不够完美。

关于 python 的 "bad" 事情之一是它的文档因异常之类的事情而受到影响。像 Java 这样的语言,其中异常是 function/method 定义的一部分,而 return 类型更严格。基本上,试着记住 Python 的禅宗,然后顺其自然。 python.org/dev/peps/pep-0020

我同意现有 answers/comments 的观点,即您可以将内置函数信任 return 只有文档中说的 return,并且一些快速的自我测试应该会给您对常见极端情况的行为充满信心。但为了完整起见,让我们看得更深入一点。可以找到 CPython 的 findall 源代码 here。我们真的只对 return 语句感兴趣,它们是:

if (!state_init(&state, self, string, pos, endpos))
    return NULL;

list = PyList_New(0);
if (!list) {
    state_fini(&state);
    return NULL;
}

//...

state_fini(&state);
return list;

error:
Py_DECREF(list);
state_fini(&state);
return NULL;

所以这个函数可以return两个可能的值:一个列表,或者NULL。

此处返回 NULL 向解释器发出函数 will raise an exception. If the function wanted to return None, it would do Py_RETURN_NONE 的信号。它在这里不这样做,所以我们可以合理地假设 findall 将始终 return 一个列表,只要它不崩溃。