How can I get generics to work in Python.NET with CPython

霸气de小男生 提交于 2019-12-10 10:33:13

问题


How can I get generics to work in Python.NET with CPython. I get an error when using the subscript syntax from Python.NET Using Generics

TypeError: unsubscriptable object

With Python 2.7.11 + pythonnet==2.1.0.dev1

>python.exe
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> from System import EventHandler
>>> from System import EventArgs
>>> EventHandler[EventArgs]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsubscriptable object

I've also tried pythonnet==2.0.0 and building form github ca15fe8 with ReleaseWin x86 and got the same error.

With IronPython-2.7.5:

>ipy.exe
IronPython 2.7.5 (2.7.5.0) on .NET 4.0.30319.0 (32-bit)
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> from System import EventHandler
>>> from System import EventArgs
>>> EventHandler[EventArgs]
<type 'EventHandler[EventArgs]'>

回答1:


You can get the generic class object explicitly:

EventHandler = getattr(System, 'EventHandler`1')

The number indicates the number of generic arguments.




回答2:


That doesn't work because there are both generic and non-generic versions of the EventHandler class that exist in the System namespace. The name is overloaded. You need to indicate that you want the generic version.

I'm not sure how exactly Python.NET handles overloaded classes/functions but it seems like it has an Overloads property. Try something like this and see how that goes:

EventHandler_EventArgs = EventHandler.Overloads[EventArgs]

(this doesn't work)

It doesn't seem like Python.NET has ways to resolve the overloaded class name, each overload is treated as separate distinct types (using their clr names). It doesn't do the same thing as IronPython and lump them into a single containing type.

In this particular case, the EventArgs name corresponds to the non-generic EventArgs type. You'll need to get the appropriate type directly from the System module as filmor illustrates.



来源:https://stackoverflow.com/questions/35494331/how-can-i-get-generics-to-work-in-python-net-with-cpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!