[Ironpython-users] Implicit conversion of objects to float

Cesar Mello cmello at gmail.com
Sat Feb 25 17:25:10 CET 2012


Although implementing the arithmetic operator overloads solve my problem, I
am still curious if there is a way to implement the implicit conversion in
Python, much like the sample C# program below does. This is a question
about the language, so please forgive me if I am asking in the wrong
mailing list.

class DataValue


    public double Value { get; set; }

    public DateTime Timestamp { get; set; }

    public static implicit operator double(DataValue dataValue)


      return dataValue.Value;



  class Program


    static void Main(string[] args)


      DataValue val1 = new DataValue { Value = 2.5 };

      DataValue val2 = new DataValue { Value = 3.5 };

      double sum = val1 + val2;




Notice I did not need to implement the operator+ overload, and this object
can be used anywhere a double is. I suppose this can be done with
__coerce__ in Python 2, but that is not recommended in the documentation
(and was removed in Python 3).  Is there any other way to obtain this
behavior in Python?

I agree it may be error-prone. But there are valid scenarios where it is
not. Although implementing the arithmetic overloads allow me to mix
DataValues and floats in the same expressions, I am not able to initialize
a Python's Decimal with a DataValue, for example. In C# that could be done.

Thank you very much for the attention!

Best regards

On Fri, Feb 24, 2012 at 7:50 PM, Cesar Mello <cmello at gmail.com> wrote:

> OK thank you very much!
> Best regards
> Mello
> On Fri, Feb 24, 2012 at 6:17 PM, Jeff Hardy <jdhardy at gmail.com> wrote:
>> On Fri, Feb 24, 2012 at 12:00 PM, Cesar Mello <cmello at gmail.com> wrote:
>> > 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'.
>> Ah, you missed this first part: you'll need to overload the arithmetic
>> operators for your objects.
>> Python: Define __add__, __sub__, etc.
>> (http://docs.python.org/reference/datamodel.html#object.__add__)
>> C#: Define operator+, operator-, etc.
>> (http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx)
>> - Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20120225/66b9deec/attachment.html>

More information about the Ironpython-users mailing list