list() strange behaviour

Chris Angelico rosuav at gmail.com
Sat Jan 23 16:55:10 EST 2021


On Sun, Jan 24, 2021 at 8:49 AM Cameron Simpson <cs at cskk.id.au> wrote:
>
> On 23Jan2021 12:20, Avi Gross <avigross at 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


More information about the Python-list mailing list