PEP 255: Simple Generators

Tim Peters tim.one at home.com
Wed Jun 27 00:53:33 EDT 2001


[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, except that Icon also has
many other kinds of "special context" where generators act reasonably.

>From the examples posted here and on the Iterators list, it should be clear
that, when you stick to for-in, how you create, call, use, and think about
generators is the same as how you do all that stuff for non-generator
functions that return a list, s/result.append(x)/yield x/g.  The ability to
name the iterator object is definitely more advanced.  If an educational
implementation of Python akin to DrScheme got created, it would be good to
make the "beginner's level" raise an exception if a generator were called
outside a for-loop context.





More information about the Python-list mailing list