Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current value of generator

In Python I can build a generator like so:

def gen():
    x = range(0, 100)
    for i in x:
        yield i  

I can now define an instance of the generator using:

a = gen()

And pull new values from the generator using

a.next()

But is there a way—a.current()—to get the current value of the generator?

like image 567
Richard Avatar asked Feb 14 '14 23:02

Richard


2 Answers

There isn't such a method, and you cannot add attributes to a generator. A workaround would be to create an iterator object that wraps your generator, and contains a 'current' attribute. Taking it an extra step is to use it as a decorator on the generator.

Here's a utility decorator class which does that:

class with_current(object):

    def __init__(self, generator):
        self.__gen = generator()

    def __iter__(self):
        return self

    def __next__(self):
        self.current = next(self.__gen)
        return self.current

    def __call__(self):
        return self

You can then use it like this:

@with_current
def gen():
    x=range(0,100)
    for i in x:
        yield i

a = gen()

print(next(a))
print(next(a))
print(a.current)

Outputs:

0
1
1
like image 60
Dane White Avatar answered Nov 16 '22 15:11

Dane White


You set the value of a variable.

current_value = a.next()

then use current_value for all it's worth. Python uses this often in for statements

a = xrange(10)
for x in a:
    print(x)

Here you are defining x as the current value of a.

like image 38
Back2Basics Avatar answered Nov 16 '22 14:11

Back2Basics