Benjamin Jefferys | 13 Mar 15:53 2007

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:

... 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 

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

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:

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.


Take Surveys. Earn Cash. Influence the Future of IT
Join's Techsay panel and you'll get the chance to share your
opinions on IT & business topics through brief surveys-and earn cash