[C++-sig] dict.has_key works in a Python script, not in C++

Stefan Seefeld seefeld at sympatico.ca
Wed Mar 3 21:35:13 CET 2010


On 03/03/2010 02:10 PM, Guillaume Seguin wrote:
> I have a C++ object (named hello) exposed in a Python extension using 
> boost::python version 1.42. This code works :
>
> import my_ext
>
> aaa = my_ext.hello('aaa')
>
> d = { aaa:12345 }
>
> assert aaa in d #This assertion is true, as expected
> assert d.has_key(aaa) #This assertion is true, as expected
>
> But if I do the same thing on the C++ side, using 
> boost::python::dict::has_key, the is key is never found.
>
> #This Python code
> assert my_ext.find_key(d, aaa)
>
> //Calls this C++ code
> bool find_key(boost::python::dict d, const hello& key_to_find)
> {
>     return d.has_key(key_to_find);
> }
>
> I defined the operator == like this, but it is never called.
>
> bool hello::operator == (const hello &h) const {
>     return country == h.country;
> }
>
> And my boost class is exposed like this :
>
> using namespace boost::python;
> class_<hello>("hello", init<std::string>())
>     .def(self == self)
>     ;
>
> I tried stepping through the code with gdb, but I got lost ... What am 
> I missing ?  TIA

Python requires dictionary keys to be immutable. I wouldn't be surprised 
if it used object identity checks (such as address comparison) instead 
of a deep equal test, as a faster way to look up objects.

     Stefan


-- 

       ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list