如何创建一个具有可变返回值Python的函数



我正在用Python编写一个函数,无法找到实现允许用户选择是否计算额外数据的参数的最佳方法。它看起来大致像这个

def function(initial_sol, tolerance, compute_extra_data = False) :

solution = initial_sol
difference = 1
extra_data = []
while difference > tolerance :
newsolution = step_func(solution)
difference = diff_func(newsolution, solution)
if compute_extra_data :
extra_data.append(extra_function(newsolution))
solution = newsolution
return solution, extra_data

由于在我的实际代码中extra_function是一个更昂贵的操作,并且提供了用户可能不一定想要的额外信息,所以我希望它是可选的。然而,我真的不确定这是否是一个很好的实现方式。此外,我很想这样做,如果是compute_extra_data = False,返回值将只是solution对象,而不是同时包含两个项的元组。

我很感激和建议/想法,谢谢!

我会让你的函数更通用。与其采用决定是否附加到列表的布尔参数,不如在每个解决方案上调用一个任意函数。

def function(initial_sol, tolerance, f=None):
solution = initial_sol
difference = 1
while difference > tolerance
newsolution = step_func(solution)
difference = diff_func(newsolution, solution)
if f is not None:
f(newsolution)
solution = newsolution
return solution

然后你可以打电话给

s = function(x, t)

extra_data = []
s = function(x, lambda x: extra_data.append(extrafunction(x)))

尽管反复检查f is not None是否可能比无条件调用平凡函数更便宜,但您也可以编写

def function(initial_sol, tolerance, f=lambda x: x):
solution = initial_sol
difference = 1
while difference > tolerance
newsolution = step_func(solution)
difference = diff_func(newsolution, solution)
f(newsolution)
solution = newsolution
return solution

因为在CCD_ 5上调用身份函数只是相对昂贵的no-op。

将输出封装在字典中怎么样?

... 
out ={'solution': solution }
if compute_extra_data:
out['extra_data']: extra_data
return out

最新更新