I am exposing a C++ class using pybind11. I want to expose an __eq__ method. This is what I'm currently doing:
pybind11_class.def("__eq__", [](const MyClass &self, const myClass &other) {
return self.value == other.value;
});
The problem is that this results in a type error when comparing to objects of other types, whereas the correct behavior in that situation is for there to be no error and for the equality to evaluate to false.
How do I correctly implement the equality operator? Ideally I'd like to define only one method overload, to avoid polluting the docstring exposed by pybind11.
Instead of attempting to directly define the __eq__ method, tell pybind that you want an equality method by defining pybind11::self == pybind11::self. It will take care of the "return false for other types" semantics:
auto pybind11_class = pybind11::class_<...>(...);
pybind11_class.def(pybind11::self == pybind11::self);
pybind11_class.def(pybind11::self != pybind11::self);
For this to work, your C++ class must have operator== and operator!= operators and you must #include <pybind11/operators.h>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With