invoking yield for a generator in another function

后端 未结 5 2439
灰色年华
灰色年华 2021-02-14 16:06

suppose I have some manager object. This object\'s API has a main_hook function, that gets another function f as it\'s argument, and runs the given

5条回答
  •  独厮守ぢ
    2021-02-14 16:14

    My previous answer describes how to do this in Python2, which is very ugly. But now I ran across PEP 380: Syntax for Delegating to a Subgenerator. That does exactly what you ask. The only problem is that it requires Python3. But that shouldn't really be a problem.

    Here's how it works:

    def worker():
        yield 1
        yield 2
        return 3
    
    def main():
        yield 0
        value = yield from worker()
        print('returned %d' % value)
        yield 4
    
    for m in main():
        print('generator yields %d' % m)
    

    The result of this is:

    generator yields 0
    generator yields 1
    generator yields 2
    returned 3
    generator yields 4
    

    Exceptions are passed through the way you would expect.

提交回复
热议问题