Generators through the C API

Duncan Booth duncan.booth at invalid.invalid
Fri Jul 31 05:41:34 EDT 2009


Lucas P Melo <lukepadawan at gmail.com> wrote:

> Hello, I'm a total noob about the C API. Is there any way to create a 
> generator function using the C API? I couldn't find anything like the 
> 'yield' keyword in it.
> 
> Thanks in advance.

You define a new type with tp_flags including Py_TPFLAGS_HAVE_ITER. 
Anything that would be a local variable in your generator needs to become 
an attribute in the type.

The tp_init initialization function should contain all the code up to the 
first yield, tp_iter should return self and tp_iternext should execute code 
up to the next yield.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list