Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a correct equality operator via pybind11

Tags:

c++

pybind11

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.

like image 623
Craig Gidney Avatar asked Dec 12 '25 12:12

Craig Gidney


1 Answers

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>.

like image 171
Craig Gidney Avatar answered Dec 15 '25 05:12

Craig Gidney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!