在Bonobo-etl中,在节点中保持本地状态的最佳方式是什么



如果我有一个包含20个数字的输入队列,我如何获得例如所有数字的总和?到目前为止,这就是我想到的:

import bonobo as bb
from bonobo.config import Configurable, ContextProcessor
from bonobo.util import ValueHolder
def extract_nums():
yield 1
yield 2
yield 3
class TransformNumber(Configurable):
@ContextProcessor
def total(self, context):
yield ValueHolder({'extract':0,'transform':0})
def __call__(self, total, num, **kwargs):
total['extract']+=num
transform_num = num * 10
total['transform']+=transform_num
if num==3: # Final number
print("TOTALS:",total.get())
yield transform_num
graph = bb.Graph()
graph.add_chain(
extract_nums,
TransformNumber(),
bb.PrettyPrinter()
)

这样做可以吗?或者有更好的方法吗?

在Bonobo ETL节点中有不同的可用选项来保持本地状态。

像你那样做是可以的(尽管我认为这很难阅读(,我倾向于使用我认为更可读的闭包(但我同意,这是有争议的(:

import bonobo

def CumSum():
total = 0
def cum_sum(x):
nonlocal total
total += x
yield x, total
return cum_sum

def get_graph(**options):
graph = bonobo.Graph()
graph.get_cursor() >> range(100) >> CumSum() >> print
return graph

# The __main__ block actually execute the graph.
if __name__ == "__main__":
parser = bonobo.get_argument_parser()
with bonobo.parse_args(parser) as options:
bonobo.run(get_graph(**options))

倭黑猩猩的源代码中有几个例子,请查看https://github.com/python-bonobo/bonobo/blob/develop/bonobo/nodes/basics.py(还有不同风格的例子(。

请注意,我在这里使用Bonobo 0.7(传入(语法来构建图,但通过用add_chain调用替换">>"运算符,当前稳定版本(0.6(也可以使用相同的语法。

最新更新