Yield in a wrapper function

peterbe at gmail.com peterbe at gmail.com
Fri Nov 18 14:08:39 CET 2005


This works exactly as you would expect::

 from time import sleep
 def foo(on='ABC'):
    for e in list(on):
        sleep(1)
        yield e

When I run this on the command line It takes about 3 seconds to
complete and the first letter is shown after 1 second.
But, how do I wrap the function somewhere else::

 from time import sleep
 def foo(on):
    for e in list(on):
        sleep(1)
        yield e

 def wrapper(x):
     if x < 0:
         return foo('ABC')
     else:
         return foo('XYZ')

When I run this, variable three letters are shown and it takes 3
seconds for the whole thing to complete. The problem is that the whole
iteration is glogged up in the wrapper() function because the first
letter is shown after 3 seconds and then all letters are shown at the
same time.

How do I wrap functions that return iterators? ...if possible.




More information about the Python-list mailing list