question about generators

Tim Peters at
Fri Aug 16 00:46:06 CEST 2002

> If you haven't played with the Icon language, you should!

[Andrew Koenig]
> I have.

Cool!  Then build on that:  Python's generators are the same as Icon's
generators, except that exposing the .next() method allows Python's flavor
to be used for *some* things that require full-blown coexpressions in Icon
(driving a generator in Icon is, as in CLU too, wholly tied to control
structures -- exposing .next() allows Python's generators to be more

The syntactic sugar is different in that Icon's "suspend" *implies* "every",
but in Icon too a generator can return a result only to its immmediate
caller (ditto in CLU).

If you want something fancier than that, you have to use a coexpression in
Icon (provided your platform supports Icon coexps -- not all do), and
explicitly name the intended target coexp.  That's where your analogy to
Python's "print" breaks down:  "print" is syntactic sugar in Python for (in
part) explicitly naming sys.stdout as the intended target.  That's why it
doesn't matter from where you invoke print -- the target is global.  The
target of yield is "one up the call stack", though, and that's relative to
which function you're in.  The same is true of Icon's suspend.

There's a in the Python Demo/threads/ directory with a
different approach, using threads under the covers to allow "yielding"
values directly across any number of "stack frames".  There the producer
feeds values to a_generator.put(), and a consumer sucks them out via
a_generator.get().  Everything is explicit then, and the kinds of examples
you're writing work differently.

More information about the Python-list mailing list