Python 可以跳过“返回无”吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4027586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:54:41  来源:igfitidea点击:

Is it ok to skip "return None"?

pythonfunctionreturn-value

提问by Tomasz Wysocki

I wonder if it is bad manner to skip return None, when it is not needed.

我想知道在return None不需要时跳过是否是不好的方式。

Example:

例子:

def foo1(x):
    if [some condition]:
        return Baz(x)
    else:
        return None

def foo2(x):
    if [some condition]:
        return Baz(x)

bar1 = foo1(x)
bar2 = foo2(x)

In both cases, when condition is false, function will return with None.

在这两种情况下,当条件为假时,函数将返回None

采纳答案by rsenna

Like you said, return Noneis (almost) never needed.

就像你说的,return None(几乎)从不需要。

But you should consider that the intentionof your code is much clearer with an explicit return None. Remember: a piece of code also needs to be readable by human-beings, and being explicit usually helps.

但是,你应该考虑的是,意图你的代码是一个明确的清楚得多return None。请记住:一段代码也需要人类可读,而明确通常会有所帮助。

回答by pyfunc

Yes and No.

是和否。

In the simplest case, it is ok to skip"return None" because it returns None in only single negative condition.

在最简单的情况下,可以跳过“return None”,因为它仅在单个否定条件下返回 None 。

But if there are nested condition evaluation and multiple scenarios where a function could return None. I tend to include them as visual documentation of the scenarios.

但是,如果存在嵌套条件评估和函数可以返回 None 的多个场景。我倾向于将它们作为场景的可视化文档

[Editing: Based on comment below]

[编辑:基于下面的评论]

return or return None

返回或返回无

I prefer "return None" to bare "return"as It is explicit and later, no one will be in doubt if the return meant returning None or was it an error as something was missing.

我更喜欢“return None”而不是“return”,因为它是明确的,后来,没有人会怀疑返回是否意味着返回 None 或者它是一个错误,因为缺少某些东西。

回答by JAL

Yes, if you do not return any value from a Python function, it returns None. So, whether to explicitly return None is a stylistic decision.

是的,如果您不从 Python 函数返回任何值,它会返回 None。因此,是否明确返回 None 是一种风格决定。

Personally, I prefer to always return a value for clarity.

就个人而言,为了清晰起见,我更喜欢始终返回一个值。

回答by Ned Batchelder

To expound on what others have said, I use a return Noneif the function is supposed to return a value. In Python, all functions return a value, but often we write functions that only ever return None, because their return value is ignored. In some languages, these would be called procedures.

为了阐述其他人所说的话,我使用 a return Noneif 该函数应该返回一个值。在 Python 中,所有函数都返回一个值,但我们经常编写只返回 None 的函数,因为它们的返回值被忽略。在某些语言中,这些将被称为过程。

So if a function is supposed to return a value, then I make sure all code paths have a return, and that the return has a value, even if it is None.

因此,如果一个函数应该返回一个值,那么我要确保所有代码路径都有一个返回值,并且该返回值有一个值,即使它是 None。

If a function "doesn't" return a value, that is, if it is never called by someone using its return value, then it's ok to end without a return, and if I need to return early, I use the bare form, return.

如果一个函数“不”返回一个值,也就是说,如果有人使用它的返回值从来没有调用它,那么结束而不返回是可以的,如果我需要提前返回,我使用裸形式,return.

回答by Tony Veijalainen

def foo1(x):
    try:
        return Baz(x)
    except:
        raise ValueError('Incorrect value fo Bac')

or

或者

def foo3(x):
    return Baz(x) if <condition> else False

I do not believe in half defined function, but this False can be usefull in search type failure pruning.

我不相信半定义函数,但是这个 False 在搜索类型失败修剪中很有用。

回答by pillmuncher

The more I think about it, the less I think the case you describe shows good practice. It forces the client to discriminate, so client code would almost always look like:

我想得越多,我就越不认为你描述的案例表明了良好的做法。它强制客户端进行区分,因此客户端代码几乎总是如下所示:

b = foo1(123)
if b is not None:
    ...

You couldn't even write:

你甚至不能写:

if b:
    ...

since, if Baz.__nonzero__is overwritten, b could evaluate to False, even if it's not None. It would be better to have a Null-Bazinstance (AKA Null Object), e.g.:

因为,如果Baz.__nonzero__被覆盖,b 可能评估为 False,即使它不是 None。最好有一个Null-Baz实例(AKA Null Object),例如:

class Baz(object):
    def some_method(self):
        """some action:"""
        ...
    ...

class BazNull(Baz):
    def some_method(self):
        """nothing happens here"""
    ...

Baz.Null = BazNull()

...

def foo1(x):
    if some_condition:
        return Baz(x)
    else:
        return Baz.Null

...

b = foo1(123)
b.some_method()

The point is: help the client (who might be yourself!) to keep Cyclomatic Complexitylow. The fewer branches, the better.

关键是:帮助客户(可能是你自己!)保持低圈复杂度。分支越少越好。

回答by Granitosaurus

I disagree with a lot of the answers here.
Explicit is better than implicit but sometimes less is more when it comes to readability.

我不同意这里的很多答案。
显式比隐式好,但有时在可读性方面,少即是多。

def get_cat():
    if cat_is_alive():
        return Cat()
# vs     

def get_cat():
    if cat_is_alive():
        return Cat()
    return None

In this particular example you have 2 extra lines that really provide no beneficial information since all functions return None by default.

在这个特定的示例中,您有 2 行额外的行,它们实际上没有提供任何有用的信息,因为默认情况下所有函数都返回 None。

Additionally explicitness of return Nonedisappears even more with the usage of type hints:

此外,return None随着类型提示的使用, 的显性消失得更多:

def get_cat() -> Union[Cat, None]:
    if cat_is_alive():
        return Cat()

Including return Nonehere is a double redundancy: None is returned by default and it's indicated explicitly in the type hint markup.

return None这里包含一个双重冗余:默认情况下不返回 None 并且它在类型提示标记中明确指示。

Imho avoid trailing return Nonethey are absolutely pointless and ugly.

恕我直言,避免尾随return None他们绝对毫无意义和丑陋。