Yield in a wrapper function

Peter Otten __peter__ at web.de
Fri Nov 18 14:50:53 CET 2005


peterbe at gmail.com wrote:

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

Just 

for e in on:
    #...

is better. The list() constructor defeats much of the laziness you gain by
using a generator.

>         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.

The code you presented is OK. Your diagnosis is probably the result of a of
a misconstrued test case. Something like

for s in wrapper(1):
    print s,
    
seems to work like you described because the text is buffered until the line
is complete. Try

for s in wrapper(1):
    print s

or

import sys
for s in wrapper(1):
    print s,
    sys.stdout.flush() # explicitly flush the buffer

instead.

Peter









More information about the Python-list mailing list