I'm using a generator function, say:
def foo():
i=0
while (i<10):
i+=1
yield i
Now, I would like the option to copy the generator after any number of iterations, so that the new copy will retain the internal state (will have the same 'i' in the example) but will now be independent from the original (i.e. iterating over the copy should not change the original).
I've tried using copy.deepcopy but I get the error:
"TypeError: object.__new__(generator) is not safe, use generator.__new__()"
Obviously, I could solve this using regular functions with counters for example. But I'm really looking for a solution using generators.
listand iterate thelistmultiple times, oritertools.teemight help. It doesn't copy the generator, though, it just stores up results in a queue and spits them out again later. So any side-effects your function has won't be executed again when you read the "copy" (which presumably is what you'd want from a true clone of a generator), and if you read from the "copies" it will advance the underlying generator -- once you've teed you basically need all readers to use tees, not the original. - Steve JessopDefineis not legal python. The correct keyword isdef- SethMMortonDefis not legal either. Justdef. - SethMMorton