Lambda the Ultimate

inactiveTopic Generator-based state machines
started 7/16/2002; 2:52:54 PM - last post 7/18/2002; 2:23:10 AM
Ehud Lamm - Generator-based state machines  blueArrow
7/16/2002; 2:52:54 PM (reads: 2011, responses: 3)
Generator-based state machines
(via Daily Python-URL)

Coroutines are an "exotic" flow mechanism that few widely-used languages allow (not even non-Stackless Python). Python's new generators, however, get you almost all the way to coroutines, and the extra few steps can be faked.

Another instalment of the useful IBM developerWorks Charming Python series.

Generators and coroutines can be compared to a programming model based threarding.


Posted to Python by Ehud Lamm on 7/16/02; 2:54:10 PM

Wouter van Oortmerssen - Re: Generator-based state machines  blueArrow
7/17/2002; 7:11:15 AM (reads: 543, responses: 0)
does anyone know wether the semantics of these "generators" have special limitations (like the yield having to occur directly in the generator body) to avoid every generator needing its own stack copy?

scruzia - Re: Generator-based state machines  blueArrow
7/17/2002; 10:15:17 AM (reads: 536, responses: 0)
Yes, they do have that limitation. I don't see it written out explicitly, though, either in the PEP about generators

http://www.python.org/peps/pep-0255.html

or in Andrew Kuchling's less formal description from his "What's new in Python 2.2" document:

http://www.amk.ca/python/2.2/index.html

The restriction is implied in both docs, though: The latter doc includes:

Any function containing a yield statement is a generator function; this is detected by Python's bytecode compiler which compiles the function specially as a result.

and the former one includes:

The yield statement may only be used inside functions. A function that contains a yield statement is called a generator function.

Wouter van Oortmerssen - Re: Generator-based state machines  blueArrow
7/18/2002; 2:23:10 AM (reads: 525, responses: 0)
from the pep:

By "frozen" we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack

So I guess they do make a copy of the stack, though I guess in most cases this will just be a few items so not that expensive (a lot cheaper in terms of memory than having an own stack anyway).