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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With