Python3在脚本中控制流,有很多步骤
我正在用Python编写一个algo(学习它只是为了编写这个algo),我正在将它分解成小块或模块,以便理解 在Python中,是否有一种干净的方法来运行一组函数,最后一次传入前一个函数的值 我现在有了这个,但可能还有十几个步骤使它看起来像一个巨大的金字塔和fo:Python3在脚本中控制流,有很多步骤,python,syntax,control-flow,Python,Syntax,Control Flow,我正在用Python编写一个algo(学习它只是为了编写这个algo),我正在将它分解成小块或模块,以便理解 在Python中,是否有一种干净的方法来运行一组函数,最后一次传入前一个函数的值 我现在有了这个,但可能还有十几个步骤使它看起来像一个巨大的金字塔和fo: calculate_excess_returns( calculate_returns( get_monthly_historical_returns('./assets/monthly_historical_
calculate_excess_returns(
calculate_returns(
get_monthly_historical_returns('./assets/monthly_historical_returns.csv')
)
)
我也可以这样做,但我发现它的可读性较差:
monthly_historical_returns = get_monthly_historical_returns('./assets/monthly_historical_returns.csv')
calculated_returns = calculate_returns(monthly_historical_returns)
calculated_excess_returns = calculate_excess_returns(calculated_returns)
在JavaScript中,我们有一个称为“承诺”的通用控制流,如下所示:
getJSON('story.json')
.then(function(story) {
return getJSON(story.chapterUrls[0]);
}).then(function(chapter1) {
console.log("Got chapter 1!", chapter1);
});
你可以看到,当结果出现时,它会传递结果,并且很容易遵循流程:故事的getJSON,然后是第一章的getJSON,然后告诉用户他们到了第1章
在我的algo脚本中,能够做类似的事情会很好,比如:
SomeModuleOrPackage
.startWith(get_monthly_historical_returns('./assets/monthly_historical_returns.csv'))
.then(calculate_returns)
.then(calculate_excess_returns)
只是很清楚每一步是什么。可能是某种函数数组,循环并以某种方式将值传递给下一个函数?您可以将它们放入
列表或元组中,然后循环:
var = './assets/monthly_historical_returns.csv'
for func in (get_monthly_historical_returns,
calculate_returns,
calculate_excess_returns):
var = func(var)
基本上,您需要一种外观更好的方法来编写函数。我建议您使用一些函数式编程包,例如funcy
或fn
。下面是使用第一个包的示例
import funcy
pipeline = funcy.rcompose(
get_monthly_historical_returns,
calculate_returns,
calculate_excess_returns
)
result = pipeline('./assets/monthly_historical_returns.csv')
或者,如果您不打算多次使用管道,您可以立即计算结果:
result = funcy.rcompose(
get_monthly_historical_returns,
calculate_returns,
calculate_excess_returns
)('./assets/monthly_historical_returns.csv')
这些函数从左到右执行。一个函数的输出将作为第一个参数传递给下一个函数。如果函数需要多个参数,您可以使用标准库中的functools.partial
,为函数提供其他参数,例如
import funcy
from functools import partial
composition = funcy.rcompose(
partial(func1, additional_arg_name=something),
...
)
我想你明白了。关于getJSON
示例,您可以将匿名函数(lambda
)传递到rcompose
,使代码看起来与JavaScript示例几乎相同
您可以通过pip:pip install functy