Skip to content

Added ToPythonAs<T>() #2330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}
}
}