Benjamin Jefferys | 13 Mar 15:53 2007
Picon

Re: Making a C++ Class Iterable in Python

Rob Stewart wrote:
> Given an arbitrary C++ class with begin() and end() member
> functions, what is the right recipe for making the SWIG wrapper
> for that class iterable in Python?
>   

The following is the naive approach, there may be a nice swiggian shortcut!

The interface for your "Example" structs should follow these guidelines:

http://docs.python.org/ref/sequence-types.html

... assuming you want to do stuff like:

e = Example()
for item in e:
    ........

Clearly for your case you only need to implement __iter__, but you might 
also be able to implement the other functions nicely for your container 
classes.

Then your iterator class needs to implement the iterator interface, 
which is very simple:

http://docs.python.org/lib/typeiter.html

You can add all this to your classes using stuff like:

%extend Example
{
%insert("python") %{
    def __iter__(self):
       return ExampleIterator(self)
%}
}

AFAIK SWIG and Python don't deal with const, read this amusingly 
frustrated section of the docs:

http://www.swig.org/Doc1.3/SWIGPlus.html#SWIGPlus_nn37

Basically it will ignore your const declarations so both "Example" 
structs will behave the same way. As it says in the docs - "you might 
want to consider using another tool if maintaining constness is the most 
important part of your project" ;)

Your __iter__ function should normally return a plain forward iterator. 
If you want other types of iterator over the same class/struct, then 
just write and use functions to create them, and do:

for item in e.reverseIterator():
    ......

The "for item in e" thing is some syntactic sugar to make the most 
common use case look pretty, which it does.

HTH,
Ben.

-------------------------------------------------------------------------
Take Surveys. Earn Cash. Influence the Future of IT
Join SourceForge.net's Techsay panel and you'll get the chance to share your
opinions on IT & business topics through brief surveys-and earn cash
http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV

Gmane