Possible Duplicate:
How to clone a Python generator object?
Suppose I have a generator 'stuff_to_try', I can try them one by one but if I had a method that wanted to go through the generator and that method is recursive, I want to let each recursion get a fresh new generator that starts at the first yield rather than where the last recursion left off.
def solve(something):
if exit_condition(something):
return
next_to_try = stuff_to_try.next()
while not if_works(next_to_try):
next_to_try = stuff_to_try.next()
solve(do_something(something))
Of course I can define stuff_to_try inside the recursive function but is there a better way? Is there an equivalent of stuff_to_try.clone().reset() or something?
Define the generator in a function:
def stuff_to_try():
return (i for i in [stuff, to, try])
Then each time you want a new generator, just call the function.
def solve(something):
if exit_condition(something):
return
for next_to_try in stuff_to_try():
if_works(next_to_try):
break
solve(do_something(something))
If I read your question correctly, what you actually want is this:
def solve(something):
if exit_condition(something):
return
for each in [stuff, to, try]:
if_works(each):
break
solve(do_something(something))
The simplest answer is make it a list, then it will have the behaviour you want:
stuff_to_try = [i for i in [stuff, to, try]]
Any efficiency gains from being lazy are likely to be lost by recalculating the values again and again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With