Search code examples
pythongeneratorpython-itertools

Combine two generators and preserve send method


I have a generator that I can send values to using the generator.send() method. I'd like to add to this generator after it has been made and continue using the same functions to iterate through it. I tried itertools.chain, but that returns an iterator and I get an AttributeError when I try to send values to it.

How can I combine two generators and preserve the ability to send values to them?


Solution

  • You can use yield from (refer to the docs and this answer for more details):

    def multi_generator(*gens):
        for gen in gens:
            yield from gen