0

Possible Duplicate:
Reseting generator object in Python

I often have the following problem in python: I have a generator which I am using in several calls to compute different values, like this:

mygenerator = generate_data()
value1 = compute1(mygenerator)
value2 = compute2(mygenerator)

The problem is, of course, that compute2 will find no data, since the generator has been consumed. So I am forced to "listize" the generator:

mygenerator = generate_data()
mylist = listize_generator(mygenerator)
value1 = compute1(mylist)
value2 = compute2(mylist)

Is there another method to solve this problem?

Community
  • 1
  • 1
blueFast
  • 41,341
  • 63
  • 198
  • 344
  • 3
    what does `listize_generator` do? Can you just invoke: `mylist = list(mygenerator)`? – Paolo Moretti Oct 17 '12 at 11:12
  • Indeed, that's is what it does. Is there any other solution to this problem? Having a list of the generated data can be memory intensive. – blueFast Oct 17 '12 at 11:22

1 Answers1

0

You need co-routines to send the generator output to multiple consumers.

e.g. http://www.dabeaz.com/coroutines/cobroadcast.py

I recommend reading all of http://www.dabeaz.com/coroutines/ since it's an excellent introduction.

JohnCC
  • 615
  • 7
  • 20
  • You might also want to look at tee(), from itertools: http://docs.python.org/library/itertools.html#itertools.tee – nvie Oct 17 '12 at 21:03