creating generators from function
Terry Reedy
tjreedy at udel.edu
Wed Dec 8 11:53:07 EST 2004
"Simon Wittber" <simonwittber at gmail.com> wrote in message
news:4e4a11f804120806185e65f357 at mail.gmail.com...
> I guess this changes my question to: Can I convert a function
> containing an infinite loop, into a generator which will yield on each
> iteration?
A function containing an infinite loop will never return, so it is bugged
and useless unless it does has an external effect with something like
'print xxx' within the loop. Even then, it depends on 'while True:'
actually meaning 'while <external stop signal (control-C, reset, power off)
not present>'. The obvious change for a buggy function is to insert a
yield statement. For the implicit conditional with print, change 'print'
to 'yield'.
Note 1. Many algorithm books, especially when using pseudocode, use 'print
sequence_item' to avoid language specific details of list construction.
One of the beauties of Python2.2+ is that one can replace simply 'print'
with 'yield' and have a working algorithm.
Note 2. Delving deep into CPython internals, as you are, is CPython hacking
rather than Python programming per se. Fun, maybe, but I wonder if this is
really to best way to do what you want to do.
Terry J. Reedy
More information about the Python-list
mailing list