Reputation: 519
I have 64bit CPython 3.4 installation on windows7. I use the pythonnet package (2.0.0.dev1). I want to instantiate the action delegate, but it gives me an error.
def display(num):
print("num=", num)
import clr
clr.AddReference("System")
import System
paction=System.Action[System.Int32](display)
I get this error:
TypeError Traceback (most recent call last) in () ----> 1 paction=System.Action[System.Int32](display) TypeError: unsubscriptable object
I guess this is the way one shall specify generics.
I have checked the docu and this post, and still do not see the problem. I also palyed around a bit with the Overload method, but did not help either:
paction=System.Action.Overloads[System.Int32](display)
TypeError Traceback (most recent call last) in () ----> 1 paction=System.Action.Overloads[System.Int32](display) TypeError: No match found for constructor signature
Upvotes: 5
Views: 3232
Reputation: 32278
The problem is that System.Action
(without arguments and thus not a generic) is shadowing System.Action<T>
while System.Func
maps directly to System.Func<T>
. I guess this is because System.Func
will always have a generic parameter and there seems to be an overload implementation in place for generics.
The generic's name in Python.NET is Action`1
(in general: Action`N
with N
being the number of generic arguments). You can get the wrapper object by using getattr
on the module:
Action = getattr(System, "Action`1")
action = Action[Int32](display)
Upvotes: 4
Reputation: 532
I'm also facing this problem. I created a work around to use Actions in Python.Net
Create a .net class library project with the following code:
using System;
namespace PythonHelper
{
public class Generics
{
public static Action<T1, T2> GetAction<T1, T2>(Func<T1, T2, object> method)
{
return (a, b) => method(a,b);
}
}
}
Compile this to a dll file and include it in your Python.net project (clr.AddReference('PythonHelper')
)
Now in your Python.net project you can create generics with following code:
import clr
clr.AddReference('PythonHelper')
import System
from System import DateTime, Func
from PythonHelper import Generics
def myCallback(a,b):
print a, b
func = Func[DateTime, DateTime, System.Object](myCallback)
action = Generics.GetAction[DateTime, DateTime](func)
If you need to create an action with more or less params, you have to add another GetAction method yourself.
Upvotes: 1