[Ironpython-users] Implicit conversion of objects to float

Cesar Mello cmello at gmail.com
Fri Feb 24 21:00:06 CET 2012

Thank you very much for the quick response Jeff!

First, let me clarify I am a Python newbie, so my assumptions about Python
may be all wrong.

I had tried __float__ in a Python object, but it does not work implicitly
inside expressions (and I think that's the correct behavior). You still
have to use float(a) for the conversion to be used.

Now I implemented the C# implicit conversion to double() and I get the same
behavior (it works if I use float(a) in the expression but if I use a * 5.0
for example I get the error: "unsupported operand type(s) for *:
'DataValue' and 'float'.

I could make it work with __coercion__, but the documentation says to avoid
this because it is error-prone and was discarded in Python 3.

Sorry if I am asking this question in thw wrong mailing list. Maybe it
should go to comp.lang.python.

Any other suggestion?

Thank you very much for the attention!

Best regards

On Fri, Feb 24, 2012 at 5:20 PM, Jeff Hardy <jdhardy at gmail.com> wrote:

> On Fri, Feb 24, 2012 at 10:54 AM, Cesar Mello <cmello at gmail.com> wrote:
> > Is there a way to satisfy both scenarios? So that the object could also
> be
> > evaluated implicitly as a float?
> >
> > My first thought was to use a coercion, but the documentation does not
> > recommend it. Any other suggestions please?
> You didn't specify if the objects are Python or C#, but I'm assuming C#.
> You'll need to overload + - * / on the objects to behave as you want,
> to cover basic math, and
> add an impilcit conversion to float ('implicit operator float()' in
> C#, __float__ in Python) if they decide to call sqrt() or similar.
> I'm assuming IronPython will handle the conversions properly; if not,
> file a bug because it's a pretty big problem if it doesn't.
> - Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20120224/ac98b8c5/attachment.html>

More information about the Ironpython-users mailing list