Add variable element / method to Python generator?

Is it possible to add a variable element / method to a Python generator?

I want something in the following lines so that I can "peek" into member variable j:

def foo(): for i in range(10): self.j = 10 - i yield i gen = foo() for k in gen: print gen.j print k 

Yes, I know that I can return AND j every time. But I do not want to do this. I want to look into a local generator.

+6
python generator local
source share
2 answers

You can create an object and control the __iter__ interface:

 class Foo(object): def __init__(self): self.j = None def __iter__(self): for i in range(10): self.j = 10 - i yield i my_generator = Foo() for k in my_generator: print 'j is',my_generator.j print 'k is',k 

Print

 j is 10 k is 0 j is 9 k is 1 j is 8 k is 2 j is 7 k is 3 j is 6 k is 4 j is 5 k is 5 j is 4 k is 6 j is 3 k is 7 j is 2 k is 8 j is 1 k is 9 
+9
source share

I find this ugly, but it should do what you want. I would prefer to return AND j every time, though :-)

 class Foo(object): def foo(self): for i in range(10): self.j = 10 - i yield i genKlass = Foo() gen = genKlass.foo() for k in gen: print genKlass.j print k 
+2
source share

All Articles