简体   繁体   中英

pack/unpack a generator

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.

Well, in this simple example, you could just write a = b or a = lambda: b . But if a adds elements of its own, you can use itertools.chain :

import itertools
def a():
  return itertools.chain(['a-value'], b())

Bear in mind that although this variant may be shorter, for: yield is a quite intuitive (and therefore easy to understand) pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM