[Pyrex] nagging differences / implementing generators

Bob Ippolito bob at redivi.com
Fri May 7 04:04:40 CEST 2004


On May 6, 2004, at 9:55 PM, Greg Ewing wrote:

> "David J. C. Beach" <beach at verinet.com>:
>
>> 2) building generators / allowing yield
>
>> My thought is to have a special integer variable in the extension type
>> which stores the "position" of the execution within the next()
>> function...
>>
>> Upon entering the "next" function, the C code should examine the value
>> of the "position" variable with a "switch" statement, and do a
>> computed - goto to jump to the appropriate place in the function's
>> execution.
>
> Yes, I've had similar thoughts myself. I agree it would be
> possible, although it would be a much bigger project than any
> of the others. Again, you're welcome to have a go.
>
> By the way, I think there's an easier way to to the jump than your
> switch-full-of-gotos. You might not be aware, but in C, the cases of a
> switch statement don't have to be at the level of the switch statement
> itself -- they can be inside other statements nested within the switch
> statement.  So you can do something like
>
>   switch (gen->position) {
>     case 1:
>     /* code for the first yield */]
>     case 2:
>     for (...) {
>       /* code for the print */
>       /* code for the second yield */
>       case 3: ;
>     }
>   }
>
> This could simplify things a lot, since you wouldn't have to break the
> rest of the code up into blocks with labels between them.

You also have to capture the local variables of the function and put 
them all on the heap...  I guess you would define a 
per-generator-function struct that has all of the local variables and 
free it when the generator object is dealloc'ed.. either that or you 
could just use stackless ;)

-bob





More information about the Pyrex mailing list