[Ironpython-users] Conversions from pure-Python types to .NET types

Vernon D. Cole vernondcole at gmail.com
Fri May 10 10:10:22 CEST 2013

Sounds simple, clean, and gives an expected result.  I like the idea of
using "NotImplemented".
  I almost like the idea of raising NotImplementedError better (it would be
a noisier failure) but the documentation might lead the unwary away from
the problem (a failed implicit conversion) rather than toward it, so the
returned value is probably better.

On Fri, May 10, 2013 at 12:24 AM, Jeff Hardy <jdhardy at gmail.com> wrote:

> There a few cases - decimal.Decimal, uuid.UUID - where there is a type
> implemented in Python with a corresponding type in .NET, and right now
> there's no way that I know of to allow for an implicit conversion from
> the Python type to the .NET type when calling a .NET API.
> I've been pondering this a bit and I think I have a reasonable solution:
> class MyDecimal(object):
>   def __clr_convert__(self, to):
>     if to is System.Decimal:
>       return System.Decimal(self.get_bits())
>     return NotImplemented
> NotImplemented is a standard Python value that is used to signal when
> comparison operators are not implemented for certain types; reusing it
> here seems totally natural. It can't use None because None is
> potentially a valid result, depending on the type.
> I haven't completely thought through the impact on overload resolution
> so this could be too naive to work, but it's worth a try at least. The
> issue is the cost of doing a conversion only to throw it away, but
> ideally implicit conversions are cheap anyway. An alternative would be
> similar, but with an additional hook (i.e. __clr_conversions__) that
> is/returns a tuple of all types that it can be converted to, so that
> the actual conversion isn't necessary.
> For motivation and some more use cases, see
> https://ironpython.codeplex.com/workitem/14453
> and https://ironpython.codeplex.com/workitem/33830.
> Are there an suggestions of how else this could be handled, or any
> concerns with the design? If all goes well I should be able to get
> this into 2.7.4 (Coming Soon, I swear!), but if it's too complex I
> might push it to 3.0.
> - Jeff
> _______________________________________________
> Ironpython-users mailing list
> Ironpython-users at python.org
> http://mail.python.org/mailman/listinfo/ironpython-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20130510/0a837f4b/attachment.html>

More information about the Ironpython-users mailing list