Search code examples
pythongenerator

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?


Solution

  • 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