[Ironpython-users] Conversions from pure-Python types to .NET types
jdhardy at gmail.com
Fri May 10 08:24:25 CEST 2013
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:
def __clr_convert__(self, to):
if to is System.Decimal:
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
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.
More information about the Ironpython-users