What is executed when in a generator
fredrik at pythonware.com
Tue Oct 4 14:08:09 CEST 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:
"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
"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."
More information about the Python-list