Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pack/unpack a generator

Tags:

python

I have a two generators. First generator sometimes needs to call second generator and yield back values it got from there:

def a():
    for _b in b():
        yield _b

def b():
    yield 1
    yield 2

for _a in a():
    print _a

Is there a more elegant way to do this:

for _b in b():
    yield _b

I've tried this:

yield *b()

But surely it doesn't work. I have Python 2.6.

like image 718
warvariuc Avatar asked Dec 22 '22 12:12

warvariuc


2 Answers

I think you mean PEP380. It's available from Python 3.3. It looks like:

 yield from b()

There is no special syntax for that in Python2. You just use a for-loop.

The a function in your question is actually completely useless. You can just use b in it's place.

like image 86
Jochen Ritzel Avatar answered Dec 24 '22 01:12

Jochen Ritzel


You can use a generator expression. It's about as concise as the loop, plus it indicates that your code is primarily for producing a return value instead of a side effect.

def a():
    return (_b for _b in b())

As phihag said, you can probably simply write a = b if your code is really like this example, since a and b return the same sequence.

like image 32
Heatsink Avatar answered Dec 24 '22 00:12

Heatsink