1

I have two functions (generator).

def a():
  yield 1
  yield 2


def b():
  yield 'A'
  yield 'B'
  yield a()

Now I want to iterate over b() and expect it should output A B 1 2. But no. Its giving this.

In [11]: for i in b():
   ....:     print i
   ....:     
A
B
<generator object a at 0x10fc3ddc0>

How can I get the required output?

1
  • 2
    Why would you expect A B 1 2? You're yielding the generator object itself, not its contents. Commented Mar 11, 2015 at 16:15

2 Answers 2

6

On python3.3+, you can use yield from:

def b():
    yield 'A'
    yield 'B'
    yield from a()

In versions prior to python3.3, you need to yield the values explicitly in a loop:

def b():
    yield 'A'
    yield 'B'
    for item in a():
        yield item
Sign up to request clarification or add additional context in comments.

2 Comments

My bad luck its not available on python2. But this is what I expected actually!
@ReutSharabani -- Sorry, it means I was having a hard time typing :-) You should still be able to see my comment on your now deleted post, but basically I was pushing back on the notion that yield from is simply "syntatic sugar" as it is true generator delegation -- and accomplishing the same thing prior to yield from is tricky.
1

In Python 3. You could use yield from

def a():
  yield 1
  yield 2


def b():
  yield 'A'
  yield 'B'
  yield from a()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.