我认为你的意思是协同例程,而不是协同递归。是的,这在 Python 中是完全可能的,因为PEP 342:通过增强生成器的协程已经实现。
典型的例子是消费者装饰器:
def consumer(func):
def wrapper(*args,**kw):
gen = func(*args, **kw)
next(gen)
return gen
wrapper.__name__ = func.__name__
wrapper.__dict__ = func.__dict__
wrapper.__doc__ = func.__doc__
return wrapper
Run Code Online (Sandbox Code Playgroud)
使用这样的consumer方法,我们可以链接过滤器并通过它们推送信息,充当管道:
from itertools import product
@consumer
def thumbnail_pager(pagesize, thumbsize, destination):
while True:
page = new_image(pagesize)
rows, columns = pagesize / thumbsize
pending = False
try:
for row, column in product(range(rows), range(columns)):
thumb = create_thumbnail((yield), thumbsize)
page.write(
thumb, col * thumbsize.x, row * thumbsize.y
)
pending = True
except GeneratorExit:
# close() was called, so flush any pending output
if pending:
destination.send(page)
# then close the downstream consumer, and exit
destination.close()
return
else:
# we finished a page full of thumbnails, so send it
# downstream and keep on looping
destination.send(page)
@consumer
def jpeg_writer(dirname):
fileno = 1
while True:
filename = os.path.join(dirname,"page%04d.jpg" % fileno)
write_jpeg((yield), filename)
fileno += 1
# Put them together to make a function that makes thumbnail
# pages from a list of images and other parameters.
#
def write_thumbnails(pagesize, thumbsize, images, output_dir):
pipeline = thumbnail_pager(
pagesize, thumbsize, jpeg_writer(output_dir)
)
for image in images:
pipeline.send(image)
pipeline.close()
Run Code Online (Sandbox Code Playgroud)
核心原理是Python生成器和yield表达式;后者让生成器接收来自调用者的信息。
编辑:啊,共同递归确实是一个不同的概念。请注意,维基百科文章使用 python作为示例,而且还使用 python生成器。
| 归档时间: |
|
| 查看次数: |
436 次 |
| 最近记录: |