What is executed when in a generator
Fredrik Lundh
fredrik at pythonware.com
Tue Oct 4 08:08:09 EDT 2005
Jerzy Karczmarczuk wrote:
> Could you tell me please where can I read something in depth about the
> semantics of generators? I feel a bit lost.
the behaviour is described in the language reference manual:
http://docs.python.org/ref/yield.html
"When a generator function is called, it returns an iterator known as a
generator iterator, or more commonly, a generator. The body of the
generator function is executed by calling the generator's next()
method repeatedly until it raises an exception."
the above page points to the design document, which contains the full
story:
http://www.python.org/peps/pep-0255.html
"When a generator function is called, the actual arguments are bound to
function-local formal argument names in the usual way, but no code in
the body of the function is executed. Instead a generator-iterator
object is returned; this conforms to the iterator protocol /.../
Each time the .next() method of a generator-iterator is invoked, the
code in the body of the generator-function is executed until a yield
or return statement (see below) is encountered, or until the end of
the body is reached."
</F>
More information about the Python-list
mailing list