[PyQt] SIP - %Exception for StopIteration

Matt Newell newellm at blur.com
Wed Aug 6 01:29:32 BST 2008


On Tuesday 05 August 2008 16:43:36 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!
>

I can't answer your question about StopIteration exception, but I have 
iteration working fine with my bindings by simply implementing __len__ and 
operater[].   I have no __iter__ or next functions.  There's probably more 
efficient ways to do it(especially depending on your operator[] 
implementation), but it works.

Matt



More information about the PyQt mailing list