I am considering port of a complex code from boost::python to pybind11, but I am puzzled by the absence of something like boost::python::extract<...>().check()
. I read pybind11::cast<T>
can be used to extract c++ object from a py::object
, but the only way to check if the cast is possible is by calling it and catching the exception when the cast fails. Is there something I am overlooking?
Asked
Active
Viewed 1,864 times
7

eudoxos
- 18,545
- 10
- 61
- 110
1 Answers
5
isinstance
will do the job (doc) :
namespace py = pybind11;
py::object obj = ...
if (py::isinstance<py::array_t<double>>(obj))
{
....
}
else if (py::isinstance<py::str>(obj))
{
std::string val = obj.cast<std::string>();
std::cout << val << std::endl;
}
else if (py::isinstance<py::list>(obj))
{
...
}

Faheem Mitha
- 6,096
- 7
- 48
- 83

Malick
- 6,252
- 2
- 46
- 59
-
Follow-up question: how do I use this to test if the object is a Python representation of one of my classes (that was exposed to Python via pybind11)? – Larry Gritz Oct 29 '17 at 06:58
-
2@LarryGritz idem : `py::isinstance
(obj)` . – Malick Oct 30 '17 at 09:14