Skip to content

Commit

Permalink
Added ToPythonAs<T>() extension method to allow for explicit conver…
Browse files Browse the repository at this point in the history
…sion using a specific type

fixes pythonnet#2311
  • Loading branch information
lostmsu committed Feb 27, 2024
1 parent 71ca063 commit 5be9bd5
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].

### Added

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

### Changed

### Fixed
Expand Down Expand Up @@ -960,3 +962,4 @@ This version improves performance on benchmarks significantly compared to 2.3.
[i238]: https://github.com/pythonnet/pythonnet/issues/238
[i1481]: https://github.com/pythonnet/pythonnet/issues/1481
[i1672]: https://github.com/pythonnet/pythonnet/pull/1672
[i2311]: https://github.com/pythonnet/pythonnet/issues/2311
9 changes: 9 additions & 0 deletions src/embed_tests/TestConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,15 @@ public void RawPyObjectProxy()
Assert.AreEqual(pyObject.DangerousGetAddressOrNull(), proxiedHandle);
}

[Test]
public void GenericToPython()
{
int i = 42;
var pyObject = i.ToPythonAs<IConvertible>();
var type = pyObject.GetPythonType();
Assert.AreEqual(nameof(IConvertible), type.Name);
}

// regression for https://github.com/pythonnet/pythonnet/issues/451
[Test]
public void CanGetListFromDerivedClass()
Expand Down
11 changes: 9 additions & 2 deletions src/runtime/Converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ internal static NewReference ToPython(object? value, Type type)
if (EncodableByUser(type, value))
{
var encoded = PyObjectConversions.TryEncode(value, type);
if (encoded != null) {
if (encoded != null)
{
return new NewReference(encoded);
}
}
Expand Down Expand Up @@ -334,7 +335,7 @@ internal static bool ToManagedValue(BorrowedReference value, Type obType,

if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if( value == Runtime.PyNone )
if (value == Runtime.PyNone)
{
result = null;
return true;
Expand Down Expand Up @@ -980,5 +981,11 @@ public static PyObject ToPython(this object? o)
if (o is null) return Runtime.None;
return Converter.ToPython(o, o.GetType()).MoveToPyObject();
}

public static PyObject ToPythonAs<T>(this T? o)
{
if (o is null) return Runtime.None;
return Converter.ToPython(o, typeof(T)).MoveToPyObject();
}
}
}

0 comments on commit 5be9bd5

Please sign in to comment.