generator functions in another language

hdante hdante at gmail.com
Sun May 4 23:09:02 EDT 2008


On May 4, 8:11 am, castiro... at gmail.com wrote:
> On May 4, 12:21 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>
>
>
> > En Sun, 04 May 2008 01:08:34 -0300, Marc 'BlackJack' Rintsch <bj_... at gmx.net> escribió:
>
> > > On Sat, 03 May 2008 16:39:43 -0700, castironpi wrote:
>
> > >> I'm actually curious if there's a way to write a generator function
> > >> (not a generator expression) in C, or what the simplest way to do it
> > >> is... besides link the Python run-time.
>
> > > The reference implementation of Python is written in C, so obviously there
> > > must be a way to write something like generators in C.
>
> > Yes and no. Generators are tied to frames, and frames execute Python code, not C. There is no simple way to write generators in C, but there are some generator-like examples in the itertools module.
> > See this threadhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> > --
> > Gabriel Genellina
>
> Gabriel,
> How did your attempt turn out from last May?  At first look, it's
> outside the scope of Python, but it is not the scope of C
> necessarily.  Generators offer a lot of simplicity (which I haven't
> read about extensively, but am starting to see) that could gain some
> reputation for Python.  What is the midpoint at which C could meet
> Python?
>
> There is no such thing as a 'frame' per se in C; byte code is
> integral.  As there is no such thing as suspended state without
> frames, and no such thing as generators without suspended state.  It's
> a hard thing to Google for without knowing the prior terminology for
> the work that's already been done on them in C.  What work is there?
> Are any devs interested in pursuing it?
>
> The frame implementation.
>
> http://svn.python.org/projects/python/trunk/Include/frameobject.hhttp://svn.python.org/projects/python/trunk/Objects/frameobject.c
>
> The generator code.
>
> http://svn.python.org/projects/python/trunk/Include/genobject.hhttp://svn.python.org/projects/python/trunk/Objects/genobject.c
>
> I used Microsoft's search engine (python frame generator
> site:svn.python.org , links 3 and 5) to find it.

 Isn't this guy a bot ? :-) It's learning fast. I believe there is a
"frame" in C, composed of its stack and globals. For generators in C,
you may look for "coroutines". For example, see:

http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html

 A sample code follows:

#define crBegin static int state=0; switch(state) { case 0:
#define crReturn(i,x) do { state=i; return x; case i:; } while (0)
#define crFinish }
int function(void) {
    static int i;
    crBegin;
    for (i = 0; i < 10; i++)
        crReturn(1, i);
    crFinish;
}

 The "suspended state" is saved in the static variable. It's not
necessary to save the complete "frame", only the suspended state.




More information about the Python-list mailing list