[C++-sig] V2: coerce method howto?

David Abrahams david.abrahams at rcn.com
Mon Apr 22 20:19:04 CEST 2002


I think you will find your answer here. In some ways I find it to be an
immense relief:

http://aspn.activestate.com/ASPN/Mail/Message/python-dev/1178205


The upshot is that you can ignore coerce and just overload your __add__
and __radd__ method to work with floats.

-Dave

----- Original Message -----
From: "Pearu Peterson" <pearu at cens.ioc.ee>
To: <c++-sig at python.org>
Sent: Sunday, April 21, 2002 2:43 PM
Subject: Re: [C++-sig] V2: coerce method howto?


>
> I have managed to put together a working coerce method (shown at the
end
> of this message) but then to my surprise I found that it has no
effect:
>
> >>> coerce(ex(1),2.3)
> (ex(numeric('1')), ex(numeric('2.2999999999999998224')))
> >>> ex(1).__add__(ex(2))
> ex(numeric('3'))
> >>> ex(1)+2.3
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: bad argument type for built-in operation
>
> Any ideas?
>
> Pearu
>
> PS: I hope that I am not too annoying with my experiments with V2 ;)
>
> ---------------
> #define EX_TO_PYTHON(e) boost::python::to_python_value<const GiNaC::ex
&>()(e)
> #define BASIC_FROM_PYTHON(o)
boost::python::converter::reference_from_python<const GiNaC::basic
&>(o)(o)
>
>   PyObject* ex_coerce(const GiNaC::ex & left,
>       PyObject* right) {
>      PyObject* v = PyTuple_New(2);
>      PyTuple_SetItem(v,0,EX_TO_PYTHON(left));
>      if (PyInt_Check(right))
>        PyTuple_SetItem(v,1,EX_TO_PYTHON(*(new
>           GiNaC::ex(PyInt_AS_LONG(right)))));
>      else if (PyFloat_Check(right))
>        PyTuple_SetItem(v,1,EX_TO_PYTHON(*(new
>           GiNaC::ex(PyFloat_AS_DOUBLE(right)))));
>      else if (PyObject_IsInstance(right,
>
(PyObject*)boost::python::objects::class_object<GiNaC::ex>::reference))
{
>        Py_INCREF(right);
>        PyTuple_SetItem(v,1,right);
>      } else if (PyObject_IsInstance(right,
>
(PyObject*)boost::python::objects::class_object<GiNaC::basic>::reference
)) {
>        PyTuple_SetItem(v,1,EX_TO_PYTHON(*(new
>          GiNaC::ex(BASIC_FROM_PYTHON(right)))));
>      } else {
>        Py_DECREF(v);
>        Py_INCREF(Py_None);
>        return Py_None;
>      }
>      return v;
>   }
>
>
>
>
>
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig







More information about the Cplusplus-sig mailing list