Search code examples
pythonobjectstreamgenerator

Reusing; i.e., continuing in stream of a python data generator in a class


I wrote the following example class, which features a generator -- in this case a range object.

class tmp():

    def _setgen(self):
        self.gen = range(1,5)

    def __init__(self):
        self._setgen() # I define my generator only once; here in the __init__()

    def getval(self):

        for g in self.gen: # use the afore defined `gen`
            print(g)
            if g > 2:
                break


t = tmp() # init the object; including the range within the object

t.getval() # As expected numbers 1,2,3

t.getval() # Expect Number 4; but get again 1,2,3

Why is the range object resetted? I want to continue, where I stopped at the break. So the second call of t.getval() should print a 4, and not operate on a new (?) range object from start again.

And what is a work around to get my "desired behaviour"?


Solution

  • self.gen = iter(range(1, 5))
    

    would do the trick. gen should be the iterator over the range if you want to keep that as the state.

    the for loop in your getval wraps the range in a fresh iter every time you call it.