Evaluating a 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 C ++ code, I retrieve the floats as follows:

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

This is clearly problematic when the 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 obviously boost :: python :: api :: object () is None. However, none of them work. How can I check this list [i] in a python None object?

+4
source share
1 answer

Your last approach compared to boost::python::api::object() should work. However, it checks if the item is actually None . Extraction may still fail if the value is not None and not a numeric type (for example, a string).

You should use check() to make sure 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 } 
+4
source

Source: https://habr.com/ru/post/1447058/


All Articles