generator function within a generator function doesn't execute?

Michael Sparks zathras at
Fri Jul 25 10:48:33 CEST 2003

Whereever you have this:
>     sleep(1.5)

You need to _run_ your generator - the above call just _creates_ the
generator. ie you'd change the above line to:

   for i in sleep(1.5):
      yield None

You've got the idea elsewhere AFAICT, just that you haven't chained the
execution of generators. (Generators don't nest - the yield keyword
instantly turns the function into a generator)

Chaining generators:

if 1:
   def n_plus2():
      while 1:
         yield value

   def n_plus1():
      while 1:
         for i in n_plus2():
            yield (anotherValue,i)

   def n():
      while 1:
         for i in n_plus1():
            yield (yetAnotherValue,i)

   for i in n():
      print i

> expected.  Why doesn't the sleep() function execute?

In summary - it doesn't run because you're not iterating through the
generator created by your sleep function. You need to do this, and in
order to pass control back to your scheduler you need to yield a value
back whilst you iterate through.

Hope that helps,


More information about the Python-list mailing list