What is executed when in a generator

Matt Hammond matt.hammond at rd.bbc.co.uk
Tue Oct 4 08:17:01 EDT 2005


On Tue, 04 Oct 2005 12:48:03 +0100, Jerzy Karczmarczuk  
<karczma at info.unicaen.fr> wrote:

> before the yield, this doesn't get executed either. *EVERYTHING*
> from the beginning until the yield gets executed only upon s.next().
>
> Could you tell me please where can I read something in depth about the
> semantics of generators? I feel a bit lost.
> Thank you.

This is probably what you want:

http://www.python.org/doc/2.4.2/ref/yield.html

But you've basically got the idea anyway. I think the important thing is  
to think of the generator as a factory. When called, it returns you  
something you can iterate over by calling the next() method. Think of it  
almost like instantiation. In fact, you could write something functionally  
equivalent like this:

gl=0

class GeneratorLikeBehaviour:
   def __init__(self, x):
     self.state = 0
     self.x = x

   def next(self):
     global gl
     if self.state == 0:
       g1 = x
       self.state = 1
       return x
     else:
       raise StopIteration

s=gen(1)


Unless I've made a typo, you should get exactly the same behaviour.

The difference under the bonnet is that calling the generator has less  
overheads, as it is not a true function call - stack frames etc are not  
having to be set up fully. Instead they are (presumably) set aside between  
calls to s.next()

Hope this helps


Matt
-- 

| Matt Hammond
| R&D Engineer, BBC Research & Development, Tadworth, Surrey, UK.
| http://kamaelia.sf.net/
| http://www.bbc.co.uk/rd/



More information about the Python-list mailing list