Boost logo

Boost Users :

From: Eric Niebler (eric_at_[hidden])
Date: 2006-11-11 17:21:14


Augusto Callejas wrote:
> hi-
>
> i'm writing a C++ class that i want to expose as a python class.
> one method in my class has an argument that takes in a python
> object that "implements" the iterator interface (that is the
> python object has defined "__iter__" and "__next__" and can
> be used in a "for x in y" loop).
>
> how do i go about iterating over that python object in my C++ code?
>
> for example:
>
> void my_class::method(object my_iterable_obj)
> {
> // iterate over "my_iterable_obj"
> }
>
> one method i tried was calling the "__next__" method explicity:
>
> my_iterable_obj.attr("__next__")()
>
> however, "__next__" raises a StopIteration exception when there
> are no more objects in the iterator. i could not find any examples
> in the boost python tutorials for handling python exceptions from c++.
>
> is there another way i can go about this?

Boost 1.34 (the next version) will come with python::stl_input_iterator,
which does exactly what you are trying to do. You can get the code now
from Boost main CVS, or look at the implementation online. The
interesting part is here: http://tinyurl.com/ybugtp.

Thing to note: if you use PyIter_Next directly instead of
obj.attr("__next__")(), you don't get an exception.

-- 
Eric Niebler
Boost Consulting
www.boost-consulting.com

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net