revive a generator

alex23 wuwei23 at gmail.com
Mon Oct 24 23:34:46 EDT 2011


On Oct 21, 11:46 am, Yingjie Lan <lany... at yahoo.com> wrote:
> I am still not sure why should we enforce that 
> a generator can not be reused after an explicit 
> request to revive it?

No one is "enforcing" anything, you're simply resisting implementing
this yourself. Consider the following generator:

  import random
  def randgen():
    for _ in xrange(10):
      yield random.choice(['Hi','Lo'])

  >>> [x for x in randgen()]
  ['Hi', 'Hi', 'Lo', 'Hi', 'Lo', 'Lo', 'Lo', 'Lo', 'Hi', 'Hi']

What would you expect when you reset that generator? A newly
randomised set of values, or the _same_ set of values?

What if the generator is reading from an external source, like
temperature values? Once revived, should it return the exact same
sequence it originally did, or should it retrieve new values?

Now, no matter which decision you made, why is your expectation of
behaviour the right one? Why should the generator protocol support
your convience in particular?

If you need your generator to be re-usable, make a factory that
creates it.



More information about the Python-list mailing list