在第一次收益之前推进Python生成器功能

WGH*_*WGH 8 python exception generator

当您实例化生成器函数时,它将不会执行任何代码,直到您调用next它.

这意味着如果生成器函数包含某种初始化代码,则在迭代之前不会执行它.

考虑这个例子:

def generator(filename):
    with open(filename) as f:
        data = f.read()

    while True:
        yield data

gen = generator('/tmp/some_file')
# at this point, no generator code is executed

# initialization code is executed only at the first iteration
for x in gen:
    pass
Run Code Online (Sandbox Code Playgroud)

如果该文件不存在,则会在for循环中引发异常.我想yield在生成器迭代之前执行第一个代码之前的代码,因此初始化期间的任何异常都将在生成器实例化时引发.

有一种干净的pythonic方式吗?

use*_*ica 5

在生成器周围包装常规函数并在其中进行初始化:

def file_contents_repeated(filename):
    with open(filename) as f:
        data = f.read()
    return _gen(data)

def _gen(data):
    while True:
        yield data
Run Code Online (Sandbox Code Playgroud)

(在这种情况下,你可以用内置发生器替换itertools.repeat,但一般不能.)


Jar*_*uen 5

函数包装器解决方案工作正常。如果您想将所有代码保留在同一个函数中,您可以创建一个闭包。

def generator(filename):
    with open(filename) as f:
        data = f.read()

    def _generator():
        while True:
            yield data

    return _generator()
Run Code Online (Sandbox Code Playgroud)