Python 1.6 The balanced language

Neel Krishnaswami neelk at brick.cswv.com
Thu Sep 7 20:33:47 EDT 2000


Just van Rossum <just at letterror.com> wrote:
> Tim Peters wrote:
> > [ Generators ]
> >
> > people who like buzzwords <wink>, Knuth calls Icon-style generators
> > "semi-coroutines"; I've sometimes, and with a bit of success, tried
> > to call them "resumable functions" on comp.lang.python, to take
> > away some of the mystery.  In a sense, they do for function-local
> > control flow what C "static" does for function-local data:
> > preserves it "across calls/resumptions".
> 
> How would you spell resuming a suspended function?

Here's one possible spelling -- this a generator for the first n
squares, using the relation that n**2 = 1 + 3 + 5 + ... + (2n-1),
and "suspend" as the magic keyword. 

>>> def squares(n):
...     i = 1
...     s = 1
...     while i <= n:
...         i = i + 1
...         s = s + (2*i - 1)
...         suspend s
...
>>> for s in squares(5):
...     print s
1
4
9 
16
25

One nice thing about generators is that they have exactly the right
semantics to represent iterating over a sequence of values, so the
ordinary for loop can be the spelling of iterating over the values of
a generator.


Neel



More information about the Python-list mailing list