Generators through the C API

L

Lucas P Melo

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.
 
S

Stefan Behnel

Duncan said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top