wrapping yield ?

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Sep 13 04:26:51 EDT 2002


"Michael Sparks" <Michael.Sparks at rd.bbc.co.uk> wrote in 
news:alqehl$9qv$1 at nntp0.reith.bbc.co.uk:

> I'd like to be able to wrap "yield"  in a function - is that
> possible, and if not (my eading of stuff  I've seen so far
> says not) are there any plans to make it possible?
> 
> Whilst it may seem odd, I'd like to be able to do this:
> 
> def my_generator(arg):
>     dostuff....
>     while(1):
>        waitForSomethingCheckingPeriodically()
>        processit
> 
> where
> 
> def waitForSomethingCheckingPeriodically():
>    found = 0
>    while(not found):
>        x = checkTheThing()
>        if foundRightThing(x):
>            found = 1
>       else:
>          yield "foo"
>    return x
> 

You have to propogate the yield up to the top level by yielding from each 
intermediate generator, and your generator cannot return a value so you 
should yield the returned results. So something like this should work:

def my_generator(arg):
   dostuff....
   for item in waitForSomethingCheckingPeriodically():
      if item is None:
          yield None
      else:
          processit(item)

def waitForSomethingCheckingPeriodically():
   while 1:
       x = checkTheThing()
       if foundRightThing(x):
           yield x
       else:
           yield None
 

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list