Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generators that defer to sub-generators

Tags:

python

I yould like to have generators that defer to other generators, e.g.

def gx():
    for i in [1, 2, 3]:
        yield i

def gy():
    for i in [11, 12, 13]:
        yield i

def gz():
    """this should defer to gx and gy to
       generate [1, 2, 3, 11, 12, 13]"""
    for i in gx(): yield i
    for i in gy(): yield i

Is the explicit loop in gz() the only way to do this, or are there better alternatives?

like image 254
reddish Avatar asked Feb 29 '12 15:02

reddish


2 Answers

In currently released Python versions, an explicit loop is the only way to invoke sub-generators. (I presume your example is just, well, an example -- not the exact problem you want to solve.)

Python 3.3 will add the special syntax yield from for this purpose:

def gz():
    """this should defer to gx and gy to
       generate [1, 2, 3, 11, 12, 13]"""
    yield from gx()
    yield from gy()

See PEP 380 for further details.

like image 135
Sven Marnach Avatar answered Sep 25 '22 15:09

Sven Marnach


Using itertools.chain:

import itertools

gz = itertools.chain(gx(), gy())

In the documentation of chain they describe it by implementation:

def chain(*iterables):
    for it in iterables:
        for element in it:
            yield element

You can draw inspiration from this as well :)

like image 38
Magnus Hoff Avatar answered Sep 21 '22 15:09

Magnus Hoff