Search code examples
pythongeneratoryield

Python - is there any way to organize a group of yields in sub function to yield outside the main function?


I have a newbie question for python gurus.

I have function A that hold a lot of repeated yield-actions like so:

yield a
yield b
yield c

so it looks like:

def funA():
    …
   yield a
   yield b
   yield c
    …
   yield a
   yield b
   yield c
    …
   yield a
   yield b
   yield c

Is there any way to put all repeated yields in function and do something like that?:

def funA():
    …
   yield funB()
    …
   yield funB()
    …
   yield funB()

Update

yield a
yield b
yield c

It's just an example but in a real application its more complex sequence of yields that repeat more then once in main generator (so it's not question about organizing yields) but about sub-generators. So I'd like to avoid code duplication.


Solution

  • If you're using the latest and greatest python (>= 3.3), there's the yield from construct.

    yield from funB()
    

    It does exactly what you want: you can invoke a function as a sub-generator, and yield back everything it yields to you.

    If you're using an earlier version of python, then I'm afraid you'll have to do it manually:

    for x in funB(): yield x
    

    If you have a dynamic set of sub-generators, you can do this:

    funs = [funA, funB, funC]
    
    for fun in funs:
        for item in fun():
            yield item