Yield in a wrapper function

Bengt Richter bokr at oz.net
Fri Nov 18 15:32:21 EST 2005


On 18 Nov 2005 05:08:39 -0800, "peterbe at gmail.com" <peterbe at gmail.com> wrote:

>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.
>
Make the wrapper itself an iterable? E.g., is this the effect you wanted?

 >>> from time import sleep
 >>> def foo(on):
 ...     for e in on:
 ...         sleep(1)
 ...         yield e
 ...
 >>> def wrapper(x):
 ...     if x < 0:
 ...         for e in foo('ABC'): yield e
 ...     else:
 ...         for e in foo('XYZ'): yield e
 ...
 >>> wrapper(-1)
 <generator object at 0x02EF3D8C>
 >>> import sys
 >>> for c in wrapper(-1): sys.stdout.write(c); sys.stdout.flush()
 ...
 ABC>>>
 >>> for c in wrapper(+1): sys.stdout.write(c); sys.stdout.flush()
 ...
 XYZ>>>

Regards,
Bengt Richter



More information about the Python-list mailing list