question about generators
Andrew Koenig
ark at research.att.com
Wed Aug 14 11:38:20 EDT 2002
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? Obviously, replacing
for i in f():
yield i
by
yield f()
won't work -- nor should it, because the compiler doesn't know that
I might not be intending to write a generator that yields a sequence
of genrators.
--
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark
More information about the Python-list
mailing list