How to clone a Python generator object? How to clone a Python generator object? python python

How to clone a Python generator object?


You can use itertools.tee():

walk, walk2 = itertools.tee(walk)

Note that this might "need significant extra storage", as the documentation points out.


If you know you are going to iterate through the whole generator for every usage, you will probably get the best performance by unrolling the generator to a list and using the list multiple times.

walk = list(os.walk('/home'))


Define a function

 def walk_home():     for r in os.walk('/home'):         yield r

Or even this

def walk_home():    return os.walk('/home')

Both are used like this:

for root, dirs, files in walk_home():    for pathname in dirs+files:        print os.path.join(root, pathname)