我正在尝试将一个更大的函数(比如搜索trie)分解为具有嵌套协同路由的生成器。生成器接收值,将其发送到协程,并生成最终输出(如果有)
def filter_pipe(func, target):
while True:
node = (yield)
term = (yield)
node = func(node, term)
if node:
target.send(node)
def and_in_the_end():
while True:
node = (yield)
yield node
yield node
每个协同路由都有一个表达式,它是发送到目标的条件基础
source(node, term)
在隔离时返回更新的值
def source(node, term):
sink = and_in_the_end()
sink.__next__()
funcs = [good_node, naughty_node]
for func in funcs:
target = filter_pipe(func, sink)
target.__next__()
target.send(node)
target.send(term)
result = sink.__next__()
return result
print(source('node', 'node')) --> 'node was good'
print(source('node', 'other')) --> 'node was naughty'
在生成器内嵌套后branch(funcs)
:
def branch(funcs):
while True:
node = (yield)
term = (yield)
def source(node, term):
# funcs = [good_node, naughty_node] <-- removed
...
yield source(node, term)
x = branch([good_node, naughty_node])
x.__next__()
x.send('node')
x.send('term')
y = x.__next__()
print(y) --> 'None'
仅仅是从branch编写要打印的代码给了我不好的感觉,但它从何而来?这通常是一种使用发电机的坏方法吗
目前没有回答
相关问题 更多 >
编程相关推荐