Sunday, 15 September 2013

python - How to create a generator function that calls generator functions -



python - How to create a generator function that calls generator functions -

consider next (non-working) illustration code:

class mygenerator: def test_gen(self): in range(1,5): if % 2: self.foo(i) else: self.bar(i) def foo(self, i): yield def bar(self, i): yield i**2 g = mygenerator() in g.test_gen(): print

this not work, because test_gen has no yield , no longer generator function. in little illustration homecoming values foo , bar , set yield test_gen, have case that's not possible. how can turn test_gen generator function again?

you need loop on results of delegated generators , yield those:

def test_gen(self): in range(1,5): if % 2: res in self.foo(i): yield res else: res in self.bar(i): yield res

if using python 3.3 or up, you'd utilize yield from expression proper generator delegation:

def test_gen(self): in range(1,5): if % 2: yield self.foo(i) else: yield self.bar(i)

both re-introduce yield function, 1 time 1 time again making generator function.

python generator

No comments:

Post a Comment