What is executed when in a generator

Jerzy Karczmarczuk karczma at info.unicaen.fr
Tue Oct 4 14:57:37 CEST 2005

Thank you all for some precisions about yield and generators.
But I would like to underline that I am *not* a complete newbie,
and I understand this stuff in general. I read the yield.html
material quite a time ago. But thank you for the PEP, I should
have scanned it more carefully.

My problem was the *context of suspension*. You see, when some text
speaks about the preservation of local state, etc., *a priori* the
following sequence

def gen()
   yield x
   yield y

*COULD BE* understood as follows. Upon the call s=gen(), a, b and c
*get* executed, change the global state, install some local, and then
the system makes the snapshot, and returns the generator with its
context. The call to next returns x to the caller, but the generator
works for some time, and executes d, e and f before the next suspension.

Now I know that this is not true. The CO- flag of the gen() procedure
inhibits the execution of the code altogether, and a, b, c are executed
upon the first s.next; d, e and f - upon the second next. Etc. OK,
that's it, I accept such behaviour, although the alternative could be
interesting as well.


Steve Holden wrote:

> The first hing you need to realise is that s is a generator, and it 
> needs to be used in an iterative context to see the (sequence of) 
> yielded results:

This is not exact, this is a *particular* consumer view of generators.
I don't want them for iterators, I use them as emulators of *lazy
programming*, I implement some co-recursive algorithms with them.
So i use next() when I wish, and never 'for'.

Thank you once more.

Jerzy Karczmarczuk

More information about the Python-list mailing list