Re: Generators through the C API

2009-08-07 Thread Stefan Behnel
Duncan Booth schrieb:
 Lucas P Melo lukepada...@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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generators through the C API

2009-07-31 Thread Duncan Booth
Lucas P Melo lukepada...@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
-- 
http://mail.python.org/mailman/listinfo/python-list