Python/C API

Oren Tirosh oren-py-l at hishome.net
Thu Apr 10 09:23:59 CEST 2003


On Thu, Apr 10, 2003 at 02:34:13AM -0400, Jp Calderone wrote:
>   How does one write generators in C, or does one not?
> 

You can write something similar to Python generators using Duff's Device.

#define GEN_BEGIN(switch(self->state) { case 0:
#define GEN_END case -1: } return NULL;
#define GEN_YIELD(value) self.state = __LINE__; return (value); case __LINE__:
#define GEN_RETURN(value) self.state = -1; return (value);

PyObject* myobject_next(myobject *self)
{
    GEN_BEGIN
    while(...) {
         ...
         GEN_YIELD(...)
         ...
         if(...) {
             ...
             GEN_YIELD(...)
             ...
             if(...) {
                 GEN_RETURN(...)
             } 
         }
         ...
    }
    GEN_END
}

Local variables will not be preserved after yielding, so all state data
must be stored in the instance.

    Oren






More information about the Python-list mailing list