question about generators

Aahz aahz at pythoncraft.com
Wed Aug 14 19:06:53 EDT 2002


In article <yu993cthtpqr.fsf at europa.research.att.com>,
Andrew Koenig  <ark at research.att.com> wrote:
>
>I had a function along the following lines:
>
>        def f():
>                if <condition>:
>                        print <something>
>                else:
>                        <do something>
>                        f()
>                        <do something else>
>
>and I wanted to turn it into a generator instead of having it
>generate output directly.  My first try was to change "print"
>to "yield", and that failed horribly.
>
>Of course, what happened was that the recursive call was now
>creating a generator that was being thrown away.  To make it
>work, I had to do this:
>
>        def f():
>                if <condition>:
>                        yield <something>
>                else:
>                        <do something>
>                        for i in f():
>                                yield i
>                        <do something else>
>                
>So... my question is this:  Is there a cleaner general way of making
>this kind of program transformation? 

Not really.  The two functions are not really semantically equivalent.
Consider the necessary code had your original function instead of
"print" used "return".
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Project Vote Smart: http://www.vote-smart.org/



More information about the Python-list mailing list