You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Allow setting typed objects via PyModule.Set #2311
Right now, a .NET object can be passed to the Python scripting engine via PyModule.Set, which internally calls ToPythonDetectType(value)
We'd like to pass a certain interface that the object supports, so only methods of this interface are available for Python scripting.
I suspect that adding the overloaded method PyModule.Set or ConverterExtension.ToPython that accepts the type of the object may resolve this issue.
We were able to achieve the desired effect by using the following code:
internal static class PythonModuleExtensions
{
public static void Set(this PyModule module, string name, object value, Type type)
{
using var pyValue = Converter.ToPython(value, type);
SetPyValue(module, name, pyValue.Borrow());
}
private static void SetPyValue(PyModule module, string name, BorrowedReference value)
{
Check(module);
if (name is null)
throw new ArgumentNullException(nameof(name));
using var pyKey = new PyString(name);
var result = Runtime.PyObject_SetItem(module.variables, pyKey.obj, value);
if (result < 0)
{
throw PythonException.ThrowLastAsClrException();
}
}
private static void Check(PyModule module)
{
if (module.Reference.IsNull)
{
throw new ObjectDisposedException(nameof(PyModule));
}
}
}
However, as some of these types/methods are internal, this is only possible if we use IgnoresAccessChecksToGenerator, which we would really like to avoid.
PyModule inherits from PyObject, and PyObject has a Set method that accepts PyObject value.
Sounds like we just need an overload for ToPython that takes type parameter. I think it would be better to have both generic and non-generic variants. PR would be welcome.
Activity
dmitry-medvedev commentedon Feb 14, 2024
We were able to achieve the desired effect by using the following code:
However, as some of these types/methods are internal, this is only possible if we use IgnoresAccessChecksToGenerator, which we would really like to avoid.
lostmsu commentedon Feb 14, 2024
PyModuleinherits fromPyObject, andPyObjecthas aSetmethod that acceptsPyObjectvalue.Sounds like we just need an overload for
ToPythonthat takes type parameter. I think it would be better to have both generic and non-generic variants. PR would be welcome.dmitry-medvedev commentedon Feb 19, 2024
We've sent PR via a separate ticket:
#2323
Added `ToPythonAs<T>()` extension method to allow for explicit conver…
Added `ToPythonAs<T>()` extension method to allow for explicit conver…