PEP 255: Simple Generators

Carsten Geckeler uioziaremwpl at spammotel.com
Wed Jun 27 13:33:32 EDT 2001


On Wed, 27 Jun 2001, Tim Peters wrote:

> [Paul Prescod]
> > Others seem to want to teach them alongside other flow control
> > keywords.
>
> [Greg Ewing]
> > You might get away with teaching generators without
> > mentioning iterator objects if you say that they can
> > only be called in a special context, i.e.
> >
> >    for x in g():
> >
> > and that each time you hit a yield, the value gets
> > bound to x and the for-loop body is executed, then
> > execution resumes after the yield.
>
> That's what works for teaching generators in Icon,

Do you really mean that?  I would not start teaching Icon generators in
the context of simple looping like in

every i:= 1 to 10
do write(i)

> except that Icon also has many other kinds of "special context" where
> generators act reasonably.

This other "secial context" of expressions failing and fallback is
acutally the core idea of Icon.  Probably most of the readers of this list
are not really familiar with Icon, so some examples may be useful.
Assuming that prime() is a generator, giving all the prime numbers
starting from 2, we can do:

if (i := prime()) & (i > 7)
then write(i)			# prints 11

every (i := prime()) & (i > 7)
do write(i)			# prints 11 13 17 ...

write(prime())			# print 2

So generators in Icon an Python are very different.

Cheers, Carsten
-- 
Carsten Geckeler





More information about the Python-list mailing list