Generators and co-routines
staschuk at telusplanet.net
Fri Mar 7 06:15:52 CET 2003
Quoth Simon Wittber (Maptek):
> The .poll() method checks if the user is logged in, if not, calls the
> .login() method (which is the co-routine/generator). My problem is the
> .login() method is not being called! I put a print statement at the
> start of the function, and nothing gets printed. I am entirely unfamilar
> with python generators, if someone can enlighten me, please do so!
Calling a generator function does not execute the code in the body
of the function definition; it just creates a generator object
which can later be used to execute that code.
>>> from __future__ import generators
>>> def five_ints():
... print 'now starting five_ints'
... for i in range(5):
... yield i
<generator object at 0x814cd50>
Note that 'now starting five_ints' has not been printed.
>>> g = _
now starting five_ints
*Now* it gets printed -- when the generator is asked for its first
value, and so has to execute up to the first yield statement.
>>> while 1:
Traceback (most recent call last):
File "<stdin>", line 2, in ?
So, to use generators to simulate coroutines, you need to write a
scheduler which calls the next() method of the objects returned by
your generator functions. (Note that that's different than the
objects *yielded* by your generator functions; those values are
returned by the next() method of the generator object.)
There's a pretty good article at IBM DeveloperWorks (written by
our very own David Mertz) about using generators this way:
But this is really not the first thing you should do with
generators, if you're just learning them. Start with Mertz's
other good article, which presents them in terms of their
canonical use, as a way of writing iterators easily:
Steven Taschuk staschuk at telusplanet.net
"Telekinesis would be worth patenting." -- James Gleick
More information about the Python-list