什么是有条件地返回函数的最pythonic方法 [英] What is the most pythonic way to conditionally return a function
问题描述
我可以这样说:
<$如果(条件):
返回foo
def func2(n):
if($) func1(n)不是None:
return func1(n)
else:
return something_else
但是这种感觉不对,因为我必须调用func1(n)两次(func1(n)是一个更大的计算)。为了解决这个问题,我可以说:
pre $ def func1(n):
if(condition):
返回foo
def func2(n):
foo = func1(n)
如果foo不是无:
返回foo
else:
return something_else
但这种感觉不对,因为我认为我不应该分配一个新的变量,永远不会再次使用,只是为了检查func1是否返回None。
有没有更简单的方法来做到这一点,我不必调用func1两次,我不必创建一个新的变量?如果这个是唯一的方法,那么您推荐哪两个?我现在使用第二种方法(我将foo设置为func1返回的内容,而不是返回foo,除非foo == None)。
另外,请记住,在我的真正的代码,我调用了几个不同的函数,并且我想返回第一个不是None的代码,这只是一个简单的代码版本,它可以解决问题。
命名为func1的结果的名称相对便宜,所以我会这样做,但要写这样的函数:
def func2(n):
ret = func1(n)
如果ret不是其他东西,则返回ret something_else
Say I have 2 functions. I want func2 to return func1 UNLESS func1 returns None, in which case func2 returns something else. There are two ways that I could do this, but they both feel slightly wrong.
I could say:
def func1(n):
if (condition):
return foo
def func2(n):
if func1(n) is not None:
return func1(n)
else:
return something_else
But this feels wrong because I have to call func1(n) twice (and func1(n) is a larger computation). To get around that, I could say:
def func1(n):
if (condition):
return foo
def func2(n):
foo = func1(n)
if foo is not None:
return foo
else:
return something_else
but this feels wrong because I don't think I should have to assign a new variable that will never get used again, just to check if func1 returned None.
Is there an easier way to do this where I don't have to call func1 twice and I don't have to create a new variable? If this is the only way, which of the two would you recommend? I currently have it using the second way (Where I set foo to what func1 returned, than return foo unless foo == None)
Also, keep in mind that in my real code, I call several different functions, and I want to return the first one that is not None, this is just a simpler version of code that gets the question across.
Giving a name to the result of calling func1 is relatively cheap, so I'd do that, but write the function like this:
def func2(n):
ret = func1(n)
return ret if ret is not None else something_else
这篇关于什么是有条件地返回函数的最pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!