question about generators

Jonathan Hogg jonathan at
Thu Aug 15 09:42:49 CEST 2002

On 14/8/2002 22:27, in article yu99wuqtjfls.fsf at,
"Andrew Koenig" <ark at> wrote:

> You're quite right.  I really meant this:
>      def f():
>          for <...>
>              if <condition>:
>                      print <something>
>              else:
>                      <do something>
>                      f()
>                      <do something else>

Hmmm... that's a doozy. I'm not sure I'd want to try re-writing that without
recursion. The resulting solution would probably be completely unobvious.

I'd definitely just stick with the 'for x in f(): yield x' convention ;-)

I don't think it's so bad anyway as it reads better for me. Understanding
what a recursive algorithm is doing can be hard at the best of times, but
the for loop makes it explicit there will be multiple results at this point.
With some appropriate naming, it can be quite elegant:

    if is_something( node ):
        yield node.value
        for value in all_sub_somethings_of( node ):
            yield value

Well, maybe...


More information about the Python-list mailing list