Generators through the C API
Stefan Behnel
stefan_ml at behnel.de
Fri Aug 7 02:46:38 EDT 2009
Duncan Booth schrieb:
> 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.
This is pretty easy to do in Cython (or Pyrex), BTW. Just write a class
with an __iter__ and __next__ method, and Cython will generate the C-API
code as expected.
http://docs.cython.org/docs/special_methods.html#iterators
Note that Cython doesn't currently support the "yield" statement, but
that's certainly on the ToDo list.
http://trac.cython.org/cython_trac/ticket/83
Stefan
More information about the Python-list
mailing list