list() strange behaviour
Cameron Simpson
cs at cskk.id.au
Sat Jan 23 16:47:48 EST 2021
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
then:
g = G(9)
for x in g:
print(x)
if x == 5:
g.pos = 7
You could either fiddle the iterable class instance attributes directly
as above or provide a reset method of some kind.
If you don't need to fiddle/reset you can just write:
for x in G(9):
The two step above is so we have "g" to hand to do the fiddling.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list
mailing list