[PyQt] SIP - %Exception for StopIteration

Giovanni Bajo rasky at develer.com
Wed Aug 6 02:16:39 BST 2008


On Tue, 2008-08-05 at 16:43 -0700, Jonny Morrill wrote:
> Hello,
> 
> I have just started using sip to create python extensions for a few of
> my C++ libraries. I have had success with most everything I wanted to
> do. There is one thing I could use some help with, though. I wanted to
> use one of my C++ classes as if it were an iterable python object. To
> get this to work, I implemented the required functions in my C++ code:
> 
> (using Object as an example class name)
> 
> Item* Object::next();
> Item* Object::operator[](int index);
> Object* Object::__iter__();
> 
> When I create a python object I now can do something like:
> 
> object = Object()
> .
> .
> .
> for item in object:
>   // item is an Item object
> 
> This causes an infinite loop and I am pretty sure that it is because
> the Item* Object::next(); function is missing the raise StopIteration
> exception that is present in all python iterable objects. I think that
> using the %Exception directive in my specification file should lead me
> to a solution, but the syntax is somewhat confusing to me. I actually
> do not have mush experience with exceptions in C++ so a basic
> explanation of what needs to be coded in both the C++ and .sip file
> would be very much appreciated!!
> 
> Also, if there is a better way to do this I would be happy to hear it!

As Matt said, __len__ and operator[] are enough for object iteration.
Moreover, I wouldn't implement __len__ or next() in C++ if they didn't
make sense in that language as well (and probably they don't, at least
with that name). It's a better design to implement them within the SIP
binding through %MethodCode, so that you don't clutter your C++ code
with stuff needed for Python.

This brings us to your question: how can I make __iter__ raise
StopIteration. The answer is easy: you can do that in the %MethodCode of
that function, by calling PyErr_SetNone(PyExc_StopIteration).
-- 
Giovanni Bajo
Develer S.r.l.
http://www.develer.com




More information about the PyQt mailing list