简体   繁体   English

在Python中,如果函数的值不是None,是否有一种简洁的方法来返回函数的值?

[英]In Python, is there a clean way to return the value of a function if it's not None?

I find myself writing a lot of code that resembles the following: 我发现自己编写了许多类似于以下内容的代码:

ans = call_function()
if ans:
    return ans

...

Is there a clean way to make this a 1 or 2 liner? 是否有一种干净的方法使这个1或2班轮? An "example" of such a paradigm might be 这种范式的“例子”可能是

if x as call_function():
    return x

It seems that as long as ans is not None, you can just return it, based on your implied usage. 似乎只要ans不是None,你可以根据你的暗示用法返回它。

if ans is not None:
    return ans

I'm not sure what you're doing after your if , but perhaps you're doing the following: 我不确定你在if之后做了什么,但也许你正在做以下事情:

ans = call_function()
if ans:
    return ans
else:
    return default

In which case it you can simply do: 在这种情况下,你可以简单地做:

return call_function() or default

It may make sense to refactor the code which would follow your if statement into another function. 将您的if语句后面的代码重构为另一个函数可能是有意义的。 There is a (not unwise) school of thought which emphasizes making each function do one very specific thing. 有一种(不是不明智的)思想流派强调让每个功能做一个非常具体的事情。

In this case, you could write something like this: 在这种情况下,你可以写这样的东西:

ans = call_function()
return ans if ans is not None else following_code()

or, if you are really testing for a truthy value (rather than specifically testing for not None ): 或者,如果你真的在测试一个真正的价值(而不是专门测试not None ):

return call_function() or following_code()

In the not None case, you can still avoid assigning to the temp variable ans by writing a function like this: not None情况下,您仍然可以通过编写如下函数来避免分配给temp变量ans

def fallback(test_value, routine, *args, **kwargs):
    return test_value if test_value is not None else routine(*args, **kwargs)

and then using it like this: 然后像这样使用它:

return fallback(call_function(), following_code,
                arg_to_following_code, following_code_kwarg=keywordarg_value)

This might be useful if you're doing this sort of thing very frequently, but in general it will just make your code a bit harder to read, because people will not be familiar with your fallback function. 如果您经常这样做,这可能会很有用,但一般情况下它只会使您的代码更难阅读,因为人们不会熟悉您的fallback功能。 The original form used in your question is bulky, but it has a readily recognizable shape that people will be used to seeing. 您问题中使用的原始表单体积庞大,但它具有易于识别的形状,人们习惯于看到它。 It also does things in a very measured fashion, one logical action per line, as is the norm in Python. 它还以非常严格的方式执行操作,每行一个逻辑操作,这是Python中的标准。

On the other hand, it can be good to cut out extraneous local variables, since these can lead to bugs due to typos or confusion about scope. 另一方面,删除无关的局部变量可能是好的,因为这些变量可能由于拼写错误或范围混乱而导致错误。

Wanting to embed assignments in if statements is probably one of the more common feature requests we see for Python. 想要在if语句中嵌入赋值可能是我们在Python中看到的更常见的功能请求之一。 The problem is that such embedded assignment proposals typically only work for the very limited cases where the value you want to store and the condition you want to check are identical (eg your example falls into that trap and would be useless if you instead needed to check a more specific condition like if ans is not None: ). 问题是这样的嵌入式分配建议通常仅适用于您想要存储的值要检查的条件相同的非常有限的情况(例如,您的示例属于该陷阱,如果您需要检查,则无用一个更具体的条件, if ans is not None:

If the extra line really offends you, you can collapse the if statement to a one-liner ( if ans: return ans ). 如果额外的行真的冒犯了你,你可以if语句折叠成一行( if ans: return ans )。 A lot of people hate that style, though. 但是很多人讨厌这种风格。

However, I question your basic premise that "I want to know if this function returns something meaningful, and if it is, then that is the result of this function as well, otherwise I will fall back and calculate my result some other way" isn't sufficient justification for using a properly scoped local variable. 但是,我质疑你的基本前提是“我想知道这个函数是否返回有意义的东西,如果是,那么这也是这个函数的结果,否则我会退回并以其他方式计算我的结果”isn没有足够的理由使用适当范围的局部变量。

Knowing whether or not another function has finished the job for you sounds pretty damn important to me. 知道另一个功能是否已经完成了你的工作听起来对我来说非常重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM