What is executed when in a generator

Steve Holden steve at holdenweb.com
Tue Oct 4 08:28:26 EDT 2005


Jerzy Karczmarczuk wrote:
> I thought that the following sequence
> 
> gl=0
> def gen(x):
>      global gl
>      gl=x
>      yield x
> 
> s=gen(1)
> 
> suspends the generator just before the yield, so after the
> assignment of s gl becomes 1.
> 
> Well, no. It is still zero. If I put
> 
> print "something"
> 
> 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.
> 

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:

  >>> s = gen(1)
  >>> s
<generator object at 0x4e028c>

The easiest way to do this is to use the generator in a loop - though of 
course in this case the sequence of yielded results is going to be of 
length 1 ...

  >>> for o in s:
  ...   print o
  ...
1
  >>>

It's easier to see the power of this when the generator yields several 
results, either from a loop or otherwise:

  >>> def shg(n):
  ...   for i in range(n):
  ...     if i % 2:
  ...       yield i
  ...
  >>> s = shg(6)
  >>> s
<generator object at 0x4e040c>
  >>> for i in s:
  ...   print i
  ...
1
3
5
  >>>

The reason for this is so you can create multiple (parameterised) 
generators using different calls:

  >>> s1 = shg(3)
  >>> s2 = shg(7)
  >>> print [i for i in s1]
[1]
  >>> print [i for i in s2]
[1, 3, 5]
  >>>

Fredrik Lundh has already pointed you to the full description, so I'll 
content myself with adding that you can, if you want to you can call the 
generator's next() method to access the next in its sequence of results:

  >>> s1 = shg(3)
  >>> s2 = shg(7)
  >>> print [(i, s2.next()) for i in s1]
[(1, 1)]
  >>> print [i for i in s2]
[3, 5]

Hope this makes things a little clearer.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list