On Tue, 04 Oct 2005 12:48:03 +0100, Jerzy Karczmarczuk <[EMAIL PROTECTED]> 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/ -- http://mail.python.org/mailman/listinfo/python-list