Generators and co-routines

Steven Taschuk staschuk at telusplanet.net
Fri Mar 7 00:15:52 EST 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.

Example:

	>>> from __future__ import generators
	>>> def five_ints():
	...     print 'now starting five_ints'
	...     for i in range(5):
	...         yield i
	... 
	>>> five_ints()
	<generator object at 0x814cd50>

Note that 'now starting five_ints' has not been printed.

	>>> g = _
	>>> g.next()
	now starting five_ints
	0

*Now* it gets printed -- when the generator is asked for its first
value, and so has to execute up to the first yield statement.

	>>> g.next()
	1
	>>> while 1:
	...     g.next()
	... 
	2
	3
	4
	Traceback (most recent call last):
	  File "<stdin>", line 2, in ?
	StopIteration

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:

<http://www-106.ibm.com/developerworks/linux/library/l-pygen.html>

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:

<http://www-106.ibm.com/developerworks/linux/library/l-pycon.html>

-- 
Steven Taschuk                  staschuk at telusplanet.net
"Telekinesis would be worth patenting."  -- James Gleick





More information about the Python-list mailing list