4

I'm new to pybind11, want to detect if a py::object isinstance of python's decimal.Decimal.

How could I write it in C++ pybind11 module ?

linrongbin
  • 2,967
  • 6
  • 31
  • 59

1 Answers1

1

You can use typeid,let assume you want to check that pi is instance of Decimal:

#include <pybind11/embed.h>
#include <iostream>
#include <typeinfo>

namespace py = pybind11;

int main() {
    py::scoped_interpreter python;
    py::object Decimal = py::module_::import("decimal").attr("Decimal");
    py::object pi = Decimal("3.14159");
    if (typeid(pi) == typeid(Decimal)) {
        std::cout << "pi is an instance of Decimal\n";
    } else {
        std::cout << "pi is not an instance of Decimal\n";
    }
}

you also can use py::isinstance function:

#include <pybind11/embed.h>
#include <iostream>
#include <typeinfo>

using namespace pybind11::literals; // to bring in the `_a` literal
namespace py = pybind11;

int main() {
    py::scoped_interpreter python;
    py::object Decimal = py::module_::import("decimal").attr("Decimal");
    py::object pi = Decimal("3.14159");
    if (typeid(pi) == typeid(Decimal)) {
        std::cout << "pi is an instance of Decimal with typeid\n";
    } else {
        std::cout << "pi is not an instance of Decimal\n";
    }
    py::dict d("spam"_a=py::none(), "eggs"_a=42);
    
    if (!(typeid(d) == typeid(Decimal))) {
        std::cout << "d is not an instance of Decimal with typeid\n";
    }

    if (py::isinstance(pi, Decimal)) {
        std::cout << "pi is an instance of Decimal with py::isinstance \n";
    }
    if (!py::isinstance(d, Decimal)) {
        std::cout << "d is not an instance of Decimal with py::isinstance\n";
    }
}

The output will be

pi is an instance of Decimal with typeid
d is not an instance of Decimal with typeid
pi is an instance of Decimal with py::isinstance 
d is not an instance of Decimal with py::isinstance
S4eed3sm
  • 1,398
  • 5
  • 20