pythondpyd

implementing iterators in pyd


I am trying to provide python iterator support to a D class wrapped with pyd.wrap_class. According to the documentation (https://github.com/ariovistus/pyd/wiki/ClassWrap#Iterator_wrapping and http://pyd.readthedocs.org/en/latest/classes.html#iterator-wrapping) the next method should return null to signal termination.

Here is my minimal D example:

import pyd.pyd;
import pyd.pydobject;
import pyd.class_wrap;

class IteratorTest
{
    IteratorTest _iter()
    {
        return this;
    }

    PydObject _next()
    {
        return null;
    }

}

extern(C) void PydMain() {
    module_init();

    wrap_class!(
        IteratorTest,
        Def!(IteratorTest._iter, PyName!("__iter__")),
        Def!(IteratorTest._next, PyName!("next"))
    );
}

However, invoking this with the python test code

for item in IteratorTest() :
    print item

prints me a never ending stream of None. Does anyone know what I am doing wrong here?


Solution

  • Thanks to DejanLekic I found the solution to the problem. The correct implementation is (note the changed signature of the _next() method):

    import pyd.pyd;
    import pyd.class_wrap;
    import deimos.python.object;
    
    class IteratorTest
    {
        IteratorTest _iter()
        {
            return this;
        }
    
        PyObject *_next()
        {
            return null;
        }
    
    }
    
    extern(C) void PydMain() {
        module_init();
    
        wrap_class!(
            IteratorTest,
            Def!(IteratorTest._iter, PyName!("__iter__")),
            Def!(IteratorTest._next, PyName!("next"))
        );
    }