Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate None object in boost python

I am passing a list of (mostly) floats to a module in boost python, some elements are None objects. In the C++ code I am extracting the floats like so:

for(i=0;i<boost::python::len(list) - window_len + 1;i++) {
  double value = boost::python::extract<double>(list[i]);
}

This is obviously problematic when list[i] points to a python None object. As such I wrote something like this:

for(i=0;i<boost::python::len(list) - window_len + 1;i++) {
  if(list[i] == NULL) continue;
  double value = boost::python::extract<double>(list[i]);
}

and

for(i=0;i<boost::python::len(list) - window_len + 1;i++) {
  if(list[i] == boost::python::api::object()) continue;
  double value = boost::python::extract<double>(list[i]);
}

because apparently boost::python::api::object() evaluates to None. However, neither of these work. How can I check that list[i] in a python None object?

like image 796
NCAggie Avatar asked Nov 19 '12 19:11

NCAggie


1 Answers

Your last approach, comparing against boost::python::api::object() should work. However, it only checks if the element it actually None. The extraction can still fail if the value is neither None nor a numeric type (a string for example).

You should use check() to ensure that the conversion was successful (if it fails, the module will throw an exception if you use the value anyway):

for( size_t i=0, len=boost::python::len(list); i<len; ++i ) {
    boost::python::extract<double> value(list[i]);
    if( !value.check() ) continue; // check if the conversion was successful
    double d = value; // now you can use value as double
}
like image 77
Anonymous Coward Avatar answered Oct 03 '22 08:10

Anonymous Coward