question about generators

Andrew Koenig ark at research.att.com
Thu Aug 15 15:19:28 CEST 2002


>> You're quite right.  I really meant this:

>> def f():
>> for <...>
>> if <condition>:
>> print <something>
>> else:
>> <do something>
>> f()
>> <do something else>

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

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

So let me bring the discussion back to my original question.  I started with

        def f():
           for <...>:
              if <condition>:
                 print <something>
              else:
                 <do something>
                 f()
                 <do something else

I wanted to change this function so that instead of printing its results,
it yielded them.  So I made the obvious change:

        def f():
           for <...>:
              if <condition>:
                 yield <something>
              else:
                 <do something>
                 f()
                 <do something else

and the program stopped working.  That's when I realized that yield wasn't
like print, and I had to write

        def f():
           for <...>:
              if <condition>:
                 yield <something>
              else:
                 <do something>
                 for i in f():
                    yield i
                 <do something else

instead.  At first I wondered if perhaps calling a generator from
another generator, and not doing anything with the results, should
automatically yield them, but decided that was too clever.  Still, I
wondered if there was an easier way of doing this program
transformation.  So far, apparently there isn't.

-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark



More information about the Python-list mailing list