some generator issues

Brendan Eich brendan at mozilla.org
Sun Apr 22 01:44:41 PDT 2007


On Apr 22, 2007, at 1:12 AM, Yuh-Ruey Chen wrote:

> There are a couple of issues I see with the generator proposal.
>
> 1) What happens when send(x) is called on a newly created  
> generator? In
> Python, this results in an exception unless x is None.

See http://developer.mozilla.org/es4/proposals/ 
iterators_and_generators.html#generators which contains this sentence:

"A generator must be started by a method call to next() or send 
(undefined). It is a TypeError to send a value other than undefined  
to a newborn generator."

> 2) What happens when a generator calls next/send on itself e.g.
>
> var $gen;
> function foo() {
>     $gen.next();   // what should this do?
>     yield;
> }
> $gen = foo();
> $gen.next();
>
> In Python, this results in an exception.

This needs to be specified; it's implemented that way in JS1.7 in  
Firefox 2. Thanks for pointing out the spec gap.

> 3) Is there any way to get a generator from within a generator  
> function?
> One use case for this would be asynchronous callbacks (can't  
> synchronous
> because of issue 2 noted above):
>
> // client calls this function somewhere
> function clientFoo() {
>     let serverResponse = yield (server.asyncProcedure 
> (clientFooGenerator));
>     print(serverResponse);
> }
>
> // server.asyncProcedure calls this once it's finished, passing
> clientFooGenerator for gen
> function serverCallback(gen, retvals) {
>     gen.send(retvals);
> }
>
> The only way to do this right now is to wrap the generator function
> within a function that introduces the iterator to the generator
> function's scope:
>
> function foo() {
>     var $gen = function() {
>        // generator code that can use $gen
>     }();
>     return $gen;
> }
>
> This is fairly inefficient and is a hassle to do.

Efficiency may be ok, depends on the implementation. Alternative to  
this FP style is an OOP approach that makes |this| for the generator  
be an instance with a var referencing the generator iterator for that  
instance.

> Other methods rely on
> some sort of generator manager (shift the responsibility to the code
> handling the generators rather than within them) or using global
> generator vars (which would force the generators to be specific to the
> script containing those vars), both of which aren't ideal in the above
> use case.
>
> I'm unaware of a Python solution to this issue.

Hard to standardize an argument; don't want another keyword.  
Suggestions?

/be



More information about the Es4-discuss mailing list