Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a member variable / method to a Python generator?

Can I add a member variable / method to a Python generator?

I want something along the following lines, so that I can "peek" at 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 i AND j every time. But I don't want to do that. I want to peek at a local within the generator.

like image 549
Joseph Turian Avatar asked Dec 21 '09 20:12

Joseph Turian


People also ask

Can you unpack a generator?

You can carry out the unpacking procedure for all kinds of iterables like lists, tuples, strings, iterators and generators.

Can a generator be called multiple times in Python?

Yes, generator can be used only once. but you have two generator object. Save this answer.

What is the difference between generator and iterator in Python?

Iterators are the objects that use the next() method to get the next value of the sequence. A generator is a function that produces or yields a sequence of values using a yield statement. Classes are used to Implement the iterators. Functions are used to implement the generator.

How do you create a generator in Python?

Create Generators in Python It is fairly simple to create a generator in Python. It is as easy as defining a normal function, but with a yield statement instead of a return statement. If a function contains at least one yield statement (it may contain other yield or return statements), it becomes a generator function.


2 Answers

You could create an object and manipulate 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

Prints:

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
like image 117
Ross Rogers Avatar answered Sep 24 '22 00:09

Ross Rogers


I think it's ugly, but it should do what you want. I'd rather return i 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
like image 32
Davide Avatar answered Sep 27 '22 00:09

Davide