Search code examples
c++pybind11

in pybind11, is it possible to determine whether a py::object is a py::dict?


If, in c++, I have an object in hand of type py::object, how can I most easily determine whether that object is a py::dict? dynamic_cast doesn't seem to work - I guess py::object isn't actually polymorphic.


Solution

  • For this purpose, pybind11 provides a C++ counterpart to Python's isinstance function.

    template<typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0> bool isinstance(handle obj)
    Return true if obj is an instance of T. Type T must be a subclass of object or a | class which was exposed to Python as py::class_.

    Since pybind11::dict is a subclass of pybind11::object, this function seems applicable. In your case, given that o is some pybind11::object, you could do

    if (pybind11::isinstance<pybind11::dict>(o)) {
         // o is a dict, do whatever is appropriate...
    }