question about generators

Steve Holden sholden at holdenweb.com
Thu Aug 15 11:08:11 EDT 2002


"Andrew Koenig" <ark at research.att.com> wrote in message
news:yu99k7ms45un.fsf at europa.research.att.com...
> >> 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.
>

But don't you think this is because of the fundamentally different nature of
"print" and "yield"? I didn't see your answer to Aahz' point, which was
(I'll repeat it here in case your server didn't catch the post):

'''
>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".
'''

I think that's a valid question.
regards
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list