[C++-sig] V2: wrapping int/double bug(?)

David Abrahams david.abrahams at rcn.com
Wed May 1 03:38:29 CEST 2002


----- Original Message -----
From: "Pearu Peterson" <pearu at cens.ioc.ee>

> Hi,
>
> It seems that V2 does not distinguish between python int and
> float types.

That's almost true, but not quite.

> For example, if one defines (note the ordering of int and double
methods)
>
>   m.add(
>     boost::python::class_<GiNaC::ex>("ex")
>
>     .def_init(boost::python::args<int>())
>     .def_init(boost::python::args<double const>())

"const" is unneccessary above, and has no effect, FWIW.

>
> .def("__add__",ex_add_double)
> .def("__add__",ex_add_int)
>   );
>
> where
>
>   const GiNaC::ex ex_add_int(const GiNaC::ex& lh,int const rh);
>   const GiNaC::ex ex_add_double(const GiNaC::ex& lh,double const rh);
>
> then in python:
>
> >>> ex(2)
> ex(numeric('2'))
> >>> ex(2.3)
> ex(numeric('2'))   <--- bug: float was converted to int
> >>> ex(0)+2
> ex(numeric('2.0')) <--- bug: int was converted to float
> >>> ex(0)+2.3
> ex(numeric('2.2999999999999998224'))
>
> That is, definitions
>      .def_init(boost::python::args<double const>())
> and
>      .def("__add__",ex_add_int)
> are ignored.

They're not ignored, but the effect ends up being the same. The built-in
numeric type converters will convert any Python object whose type
implements __float__ to a double, and any object whose type implements
__int__ to an int. The builtin numeric types all implement these
methods:

>>> 3.14.__int__()
3
>>> x = 3
>>> x.__float__()
3.0

The overloading mechanism in Boost.Python is quite simple-minded: rather
than searching for some kind of "best match", it calls the first
function whose signature can match the argument list. In Boost.Python v1
this was never a problem, but the conversion rules were less-liberal.
It's possible that liberal conversion rules are just a mistake here, but
I'm inclined to think that a more-sophisticated overloading approach
akin to multimethods would be more appropriate, as I suggest in
libs/python/doc/v2/Mar2002.html#implicit_conversions. However, that
would be a nontrivial change and I'm not prepared to put it in my
development schedule at this time.

Would it be acceptable to simply use the versions of those functions
which accept double parameters, and skip the "int" versions?

-Dave








More information about the Cplusplus-sig mailing list