On Sun, Jan 24, 2021 at 8:49 AM Cameron Simpson <c...@cskk.id.au> wrote: > > On 23Jan2021 12:20, Avi Gross <avigr...@verizon.net> wrote: > >I am wondering how hard it would be to let some generators be resettable? > > > >I mean if you have a generator with initial conditions that change as it > >progresses, could it cache away those initial conditions and upon some > >signal, simply reset them? Objects of many kinds can be set up with say a > >reinit() method. > > On reflection I'd do this with a class: > > class G: > def __init__(self, length): > self.length = length > self.pos = 0 > > def __next__(self): > pos = self.pos > if pos >= length: > raise StopIteration() > self.pos += 1 > return pos > > def __iter__(self): > return self >
Yep, or more conveniently: class G: def __init__(self, length): self.length = length self.pos = 0 def __iter__(self): while self.pos < self.length: yield self.pos self.pos += 1 The only significant part is the fact that your generator function has *external* state, which is what allows you to manipulate it. Generator functions are still way cleaner for most purposes than handwritten iterator classes. ChrisA -- https://mail.python.org/mailman/listinfo/python-list