[PyQt] SIP - %Exception for StopIteration

Jonny Morrill jrmorrill at gmail.com
Wed Aug 6 06:23:31 BST 2008


Thank you both for your help!!

@Matt:

WOW! I never new that you could create an iterable object from only the
__len__ and operator[] functions!! I must have missed that when I was
searching through the python documentation for iterator objects. It is not
clear to me which is quicker, the only difference seems to be that when you
use __iter__, you can return a copy of the object so that any modifications
will not affect the original object. Thanks again!

@Giovanni:

That seems to be exactly what I was after. I have a few questions about the
implementation though.

Since I do use the next() function as part of my C++ API i might just keep
my iteration the way it is currently. I use it to iterate similar to the
following code:

Item* Object::next()
{
  if(this->currentIndex < this->length) {
    return item[this->currentIndex];
  } else {
    return NULL;
  }
}

// In Code
Object* object = new Object;
Item* item;
while(item = object->next()) {
  // do something with item
}

Oh!! So the %MethodCode doesn't require a partner C++ function? You can
specify python specific functions inside it??

Would something like this work if I were to override the standard next()
function and not implement a __iter__() function in the C++ codebase?

class Object
{
.
.
.
%MethodCode
Item* next()
{
  if(sipCpp->currentIndex < sipCpp->length) {
    Item *item = items[sipCpp->currentIndex];
    sipCpp->currentIndex++;
    return item;
  } else {
    PyErr_SetNone(PyExc_StopIteration);
    return NULL;
  }
}

Object* __iter__()
{
  return sipCpp;
}
%End

I am sure I have some of the syntax screwed up in there (I wont be able to
test the actual code till tomorrow). Or do I need to specify the functions
above the %MethodCode like this:

class Object
{
.
.
.
Item* next();
%MethodCode
  if(sipCpp->currentIndex < sipCpp->length) {
    return item[sipCpp->currentIndex];
  } else {
    PyErr_SetNone(PyExc_StopIteration);
    return NULL;
  }
%End

Object* __iter__();
%MethodCode
  return sipCpp;
%End

I think that the only problem I have with the above solution is that the
%MethodCode would be trying to access and set some private members... If
there is no way around this I guess my only choice is to keep my next()
implementation and use the __len__() and operator[] approach.

Thanks again!!

- Jonny
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20080806/b5db190b/attachment.html


More information about the PyQt mailing list