Python 中的循环编程(corecursion)-可能吗?

Edw*_*lho 3 python

我知道Python有一些惰性实现,因此,我想知道是否可以在Python中使用循环编程。

如果不是,为什么?

Mar*_*ers 5

我认为你的意思是协同例程,而不是协同递归。是的,这在 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生成器