Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 782a0e5

Browse files
committed
allow decoders to override conversion of types derived from primitives when target type is System.Object
useful to be able to change what numpy.float64 is converted to related to pythonnet#1957 this is an alternative to pythonnet#1958
1 parent d6c024c commit 782a0e5

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

src/embed_tests/Codecs.cs

+13
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,19 @@ from datetime import datetime
355355
scope.Exec("Codecs.AcceptsDateTime(datetime(2021, 1, 22))");
356356
}
357357

358+
[Test]
359+
public void FloatDerivedDecoded()
360+
{
361+
using var scope = Py.CreateScope();
362+
scope.Exec(@"class FloatDerived(float): pass");
363+
using var floatDerived = scope.Eval("FloatDerived");
364+
var decoder = new DecoderReturningPredefinedValue<object>(floatDerived, 42);
365+
PyObjectConversions.RegisterDecoder(decoder);
366+
using var result = scope.Eval("FloatDerived()");
367+
object decoded = result.As<object>();
368+
Assert.AreEqual(42, decoded);
369+
}
370+
358371
[Test]
359372
public void ExceptionDecodedNoInstance()
360373
{

src/runtime/Converter.cs

+20-4
Original file line numberDiff line numberDiff line change
@@ -361,28 +361,44 @@ internal static bool ToManagedValue(BorrowedReference value, Type obType,
361361
// conversions (Python string -> managed string).
362362
if (obType == objectType)
363363
{
364-
if (Runtime.PyString_Check(value))
364+
if (Runtime.PyString_CheckExact(value))
365365
{
366366
return ToPrimitive(value, stringType, out result, setError);
367367
}
368368

369-
if (Runtime.PyBool_Check(value))
369+
if (Runtime.PyBool_CheckExact(value))
370370
{
371371
return ToPrimitive(value, boolType, out result, setError);
372372
}
373373

374-
if (Runtime.PyFloat_Check(value))
374+
if (Runtime.PyFloat_CheckExact(value))
375375
{
376376
return ToPrimitive(value, doubleType, out result, setError);
377377
}
378378

379-
// give custom codecs a chance to take over conversion of ints and sequences
379+
// give custom codecs a chance to take over conversion
380+
// of ints, sequences, and types derived from primitives
380381
BorrowedReference pyType = Runtime.PyObject_TYPE(value);
381382
if (PyObjectConversions.TryDecode(value, pyType, obType, out result))
382383
{
383384
return true;
384385
}
385386

387+
if (Runtime.PyString_Check(value))
388+
{
389+
return ToPrimitive(value, stringType, out result, setError);
390+
}
391+
392+
if (Runtime.PyBool_Check(value))
393+
{
394+
return ToPrimitive(value, boolType, out result, setError);
395+
}
396+
397+
if (Runtime.PyFloat_Check(value))
398+
{
399+
return ToPrimitive(value, doubleType, out result, setError);
400+
}
401+
386402
if (Runtime.PyInt_Check(value))
387403
{
388404
result = new PyInt(value);

0 commit comments

Comments
 (0)