Nov-12-2019, 10:37 PM
(This post was last modified: Nov-12-2019, 10:37 PM by Gribouillis.)
Skaperen Wrote:what i am wanting is for there to be some extra callable that causes the generator to reset during its iteration
If you really want a generator, you can pass an object as a parameter in the generator and invoke a method on that object. In the following example, I pass an object 'flag' to the generator 'mygen'. The generator calls
flag.set(False)
which returns True if the flag was previously set to True by another part of the code. Thus one can interfere with the inner mecanism of the generatorclass Flag: """An object with a boolean member 'value'""" def __init__(self): self.value = False def set(self, value): """Sets our value to a new value and return the old value""" result = self.value self.value = value return result def mygen(flag): while True: for i in range(10): if flag.set(False): # if the flag was set to True, we reset the generator break yield i else: break # test code spam = True flag = Flag() for i in mygen(flag): if spam and i == 3: flag.set(True) # this is how we tell the generator to reset itself spam = False print(i)Another solution would be to use a generator as a coroutine by using the syntax
y = yield x
, but I think it's much harder to manage.Output:0
1
2
3
0
1
2
3
4
5
6
7
8
9