GeezerVison is showing github.com — Allow setting typed objects via PyModule.Set · Issue #2311 · pythonnet/pythonnet
Allow setting typed objects via PyModule.Set #2311DescriptionEnvironment
- Pythonnet version: 3.0.1
- Python version: 3.11
- Operating System: Windows 11
- .NET Runtime: .NET 4.8
Details
- 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. Activitydmitry-medvedev commented on Feb 14, 2024 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. lostmsu commented on Feb 14, 2024 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. dmitry-medvedev commented on Feb 19, 2024 We've sent PR via a separate ticket:
#2323
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|