Python 1.6 The balanced language

Just van Rossum just at letterror.com
Fri Sep 8 06:29:16 EDT 2000


I wrote:
> How would you spell resuming a suspended function?

Neel Krishnaswami wrote: 
> 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.

Looks nice, but how does it work? does suspend really return a
sequence-like object? Or does the compiler know simply by the fact
that it contains a suspend statement that squares() should return a
sequence-like object? Could your example be rewritten like this,
and still be equivalent:

gen = squares(5)
for s in gen:
    print s

?

What exactly is 'gen' here?

Just



More information about the Python-list mailing list