不推荐在 python 中使用 `return None`。如何绕过?
我有一个使用 lxml
通过 httplib
连接到 url 的函数。它通过 xpath 检查特定模式,如果检查结果正确,则返回一个字符串。但如果检查是否定的,则不会返回任何内容。
现在的情况是,我的函数返回 None
。我调用该函数,检查其返回值是否为 not None
并继续代码。
举个例子:
def foobar(arg):
# connect to page by httplib
# check for arg in a certain pattern by lxml
if check:
return result
else:
return None
result = foobar(arg)
if result:
# do stuff
else:
# do other stuff
最近我读到,这是一个不行。我该如何避免此类情况?
I have a function which connects to a url by httplib
using lxml
. It checks by xpath
for a certain pattern and if the check is positive it returns a string. But if the check was negative it returns nothing.
Now the situation is, that my function returns None
. I call the function, check if its return value is not None
and continue in the code.
An example:
def foobar(arg):
# connect to page by httplib
# check for arg in a certain pattern by lxml
if check:
return result
else:
return None
result = foobar(arg)
if result:
# do stuff
else:
# do other stuff
Recently I read, that this is a no go. How do I avoid such situations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
返回
None
没有任何问题。在大多数情况下,您不需要显式返回
None
。 Python 会为你做这件事。这是foobar
的修改版本,其行为相同,无需显式返回None
:不过,即使 Python 隐式返回
None
,也有一个值明确;您的代码变得更容易阅读和理解。这是一个持续的权衡,没有通用的答案。There is nothing wrong with returning
None
.In most cases, you don't need to explicitly return
None
. Python will do it for you. This is an altered version of yourfoobar
which behaves identically without explicitly returningNone
:Still, even if Python implicitly returns
None
, there is a value in being explicit; Your code becomes easier to read and understand. This is a constant trade-off for which there is no general answer.我认为从可用性而非风格的角度来看,返回
None
是“不可行”。正如这个答案中简要提到的,请考虑引发异常。例如:这种方法的优点是当不存在匹配时它会变得明确。使用您的函数的其他人不需要知道
None
是他们在不匹配时应该期望的返回值,并且他们可以按照他们认为合适的方式处理异常。I think returning
None
is a "no go" from a usability standpoint rather than style. As briefly mentioned in this answer, consider raising an exception instead. For example:The advantage of this approach is that it makes it explicit when there is not a match. Other people using your function won't need to know that
None
is the return value they should expect when there isn't a match and they can handle the exception as they see fit.这取决于为什么“不行”;我没听说过。如果只是不好的形式,请完全省略“return None”(else 语句),默认情况下它将返回 None。如果认为返回 None 不好,则返回 0 或 '' (空字符串)或 False,具体取决于调用者期望的类型。
It depends on why it's a "no go"; I haven't heard that. If it's just bad form, omit the "return None" (the else statement) altogether, and it will return None by default. If it's considered bad to return None, return 0 or '' (empty string) or False instead, depending on the type expected by the caller.
处理此问题的方式有很多种,包括使用异常或仅返回所得到的任何内容,包括空白字符串。这也很好:
There are many styles of dealing with this, including using exceptions or just returning whatever you get, including a blank string. This is fine too: