----- Original Message ----- > From: "Jim Bosch" <tallji...@gmail.com> > To: "Development of Python/C++ integration" <cplusplus-sig@python.org> > Sent: Thursday, February 6, 2014 2:51:59 PM > Subject: Re: [C++-sig] returning list of class pointers that compare equal > > On Thu, Feb 6, 2014 at 2:43 PM, Gary Oberbrunner <ga...@genarts.com> > wrote: > > ----- Original Message ----- > >> From: "Jim Bosch" <tallji...@gmail.com> > > ... > >> - Add a __eq__/__ne__ overrides to the class of things you're > >> putting > >> in the list, with an implementation that compares C++ pointers, > >> not > >> Python pointers. This is almost certainly much easier, but it's a > >> little less "complete" as a solution, in the sense that you'll > >> still > >> be getting different Python objects back for the same C++ object > >> (so > >> while "param2 == param1" will succeed, "param1 is param2" will > >> still > >> fail). > > > > This is very helpful! That's OK about "is" not working, I think > > (though true, a little odd.) > > > > Can I override __hash__ too, so set membership works correctly? > > Also do I need to override __ne__; I think not? > > > > For the record, here's what I did. Defined a comparison function: > > > > static bool params_equal(Param &left, Param &right) > > { > > return &left == &right; > > } > > > > and then in the exposer: > > > > Param_exposer.def("__eq__", ¶ms_equal); > > That should be fine, as long as you don't care about what happens > when > you try to compare a Param to something else entirely (idiomatic > Python behavior would be to return False; this implementation will > likely raise an exception).
I thought about that; for some reason the above works (no exception). It never calls my params_equal code; it must have some kind of fallback. > You should be able to override __hash__ in much the same way, and I'd > recommend checking to see if __ne__ works as expected before assuming > you don't need to implement it yourself; I don't recall Python's > behavior in this case, but I think it has a tendency not to define > most operators implicitly. Just tested it, and as you suspect, indeed I do need __ne__, otherwise param1 != param2 returns True when it should return False. -- Gary Oberbrunner _______________________________________________ Cplusplus-sig mailing list Cplusplus-sig@python.org https://mail.python.org/mailman/listinfo/cplusplus-sig