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

Skip to content

Commit 9d18a24

Browse files
authored
Added ToPythonAs<T>() extension method to allow for explicit conversion using a specific type (#2330)
fixes #2311
1 parent 71ca063 commit 9d18a24

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
99

1010
### Added
1111

12+
- Added `ToPythonAs<T>()` extension method to allow for explicit conversion using a specific type. ([#2311][i2311])
13+
1214
### Changed
1315

1416
### Fixed
@@ -960,3 +962,4 @@ This version improves performance on benchmarks significantly compared to 2.3.
960962
[i238]: https://github.com/pythonnet/pythonnet/issues/238
961963
[i1481]: https://github.com/pythonnet/pythonnet/issues/1481
962964
[i1672]: https://github.com/pythonnet/pythonnet/pull/1672
965+
[i2311]: https://github.com/pythonnet/pythonnet/issues/2311

src/embed_tests/TestConverter.cs

+9
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,15 @@ public void RawPyObjectProxy()
185185
Assert.AreEqual(pyObject.DangerousGetAddressOrNull(), proxiedHandle);
186186
}
187187

188+
[Test]
189+
public void GenericToPython()
190+
{
191+
int i = 42;
192+
var pyObject = i.ToPythonAs<IConvertible>();
193+
var type = pyObject.GetPythonType();
194+
Assert.AreEqual(nameof(IConvertible), type.Name);
195+
}
196+
188197
// regression for https://github.com/pythonnet/pythonnet/issues/451
189198
[Test]
190199
public void CanGetListFromDerivedClass()

src/runtime/Converter.cs

+9-2
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,8 @@ internal static NewReference ToPython(object? value, Type type)
133133
if (EncodableByUser(type, value))
134134
{
135135
var encoded = PyObjectConversions.TryEncode(value, type);
136-
if (encoded != null) {
136+
if (encoded != null)
137+
{
137138
return new NewReference(encoded);
138139
}
139140
}
@@ -334,7 +335,7 @@ internal static bool ToManagedValue(BorrowedReference value, Type obType,
334335

335336
if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>))
336337
{
337-
if( value == Runtime.PyNone )
338+
if (value == Runtime.PyNone)
338339
{
339340
result = null;
340341
return true;
@@ -980,5 +981,11 @@ public static PyObject ToPython(this object? o)
980981
if (o is null) return Runtime.None;
981982
return Converter.ToPython(o, o.GetType()).MoveToPyObject();
982983
}
984+
985+
public static PyObject ToPythonAs<T>(this T? o)
986+
{
987+
if (o is null) return Runtime.None;
988+
return Converter.ToPython(o, typeof(T)).MoveToPyObject();
989+
}
983990
}
984991
}

0 commit comments

Comments
 (0)