question about generators

Jonathan Hogg jonathan at
Wed Aug 14 22:36:38 CEST 2002

On 14/8/2002 16:38, in article yu993cthtpqr.fsf at,
"Andrew Koenig" <ark at> 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.

I'm confused, the pattern you show above will only ever 'print <something>'
once. There are only two paths through the function, one prints, the other
calls itself recursively. So the function can only work down a bit through
some recursive calls doing <something>, then when the condition is true it
will print something, bubble back up through all the calls doing <something
else>, and exit.

So if it can only return one thing, you don't need a generator. So I'm
guessing there's something crucial missing from the pattern shown.

I was going to suggest analysing the function and turning it into a loop
instead of recursion, but I can't suggest how to do that without knowing a
bit more about how it was meant to work.

That said, I usually just do what you did and put a 'for x in f(): yield x'


More information about the Python-list mailing list