[C++-sig] call python iterable (handle StopIteration?)

François Duranleau duranlef at iro.umontreal.ca
Tue Jul 17 17:13:46 CEST 2007


On Tue, 17 Jul 2007, Neal Becker wrote:

> I want to call a python iterable from c++.  Can I do this?
>  while (true) {
>    T n = extract<T> (o.attr ("next")());
>    tmp.push_back (n);
>  }
>
> How do I (can I?) catch the StopIteration exception?

You can also try to use boost::python::stl_input_iterator (from 1.34), 
e.g.:

// here it assumed that the object o is not the iterator object itself but 
// the iterable objet, that is, an object with a method __iter__
for( stl_input_iterator< T > begin( o ) , end ;
      begin != end ;
      ++ begin )
{
     tmp.push_back( * begin ) ;
}

or

std::copy( stl_input_iterator< T >( o ) ,
            stl_input_iterator< T >() ,
            std::back_inserter( tmp ) ) ;

For more info: http://www.boost.org/libs/python/doc/v2/stl_iterator.html

-- 
François Duranleau
LIGUM, Université de Montréal


More information about the Cplusplus-sig mailing list