[C++-sig] Overriding operator == and = for None

Andreas Beyer mail at a-beyer.de
Wed Jun 21 11:22:08 CEST 2006


I think there are two things to do.
First, NullableIntVec has to define a wrapper method for __setattr_(), 
which would have to accept python objects and either create a new empty 
NullableInt or a NullableInt initialized with the respective value.

Second, you will have to wrap __eq__(), __ne__() and/or __cmp__() of 
NullableInt in order to get the desired behaviour for ==.
I suggest implementing 'rich comparison', because that would allow you 
to do things like this:

 >>> c = NullableInt(3)
 >>> c < 4
 >>> True

See also here:

Again, these wrappers will have to accept python objects (i.e. 
boost::python::object) as arguments, otherwise you can't properly 
compare against None.

Hope that helps,

Will Lee wrote:
> Is there a way I can override the operator == and = for a wrapped c++ 
> object to take in a Python None type?  Essentially, I'd like to define 
> a class where it can do:
> #NullableInt is a struct that holds an int and a boolean, indicating 
> whether it is valid or not
> c = NullableInt(3)
> # NullableInt wraps a C++ std::vector<NullableInt>
> cv = NullableIntVec()
> cv.append(c) # ok
> cv[0] = None
> print cv[0]
> # should print out "None", and the C++'s struct would hold a boolean 
> that's set to false
> # Generates an invalid Int
> cInvalid = NullableInt()
> # Should be true, it won't remove object but setting the underlying 
> c++ object to None)
> cv[0] == cInvalid
> # Should also be true if we can override ==
> cv[0] == None
> Does anybody know if it is posslbe in Boost.Python to have this behavior?
> Will
> ------------------------------------------------------------------------
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig

Dr. Andreas Beyer
mail at a-beyer.de

More information about the Cplusplus-sig mailing list