问题描述
考虑以下代码:
from typing import List,TypeVar,Callable
_T = TypeVar('_T')
# A generic function that takes a string and a list of stuff and that returns one of the stuff
Prompter = Callable[[str,List[_T]],_T]
# A function that takes such a Prompter and do things with it
ActionDef = Callable[[Prompter[_T]],None]
# A register of all ActionDef's
ACTION_DEFS: List[ActionDef[_T]] = []
我在 List[ActionDef[_T]]
上收到来自 pylance 的错误:
Type variable "_T" has no meaning in this context
如果我改用 List[ActionDef]
,它也会抱怨:
Expected type arguments for generic type alias "ActionDef"
基本上它想让我做一些像 ACTION_DEFS: List[ActionDef[int]] = []
这样的事情,这会破坏整个观点。
问题 1:如何定义 write ACTION_DEFS
类型声明?
问题 2(标题的来源):有没有办法定义 Prompter
,这样我就不需要到处都带着 [_T]
?
解决方法
您遇到的第一个错误是因为使用具有泛型类型的类型变量创建了泛型别名,而不是具体类型。您必须使用具体类型注释变量,因此会出现错误。
第二个错误,我假设它特定于 pylance
,因为在 mypy
中,未参数化的泛型类型等效于将所有类型变量替换为 Any
。所以类型 List[ActionDef]
等价于 List[ActionDef[Any]]
。
据我所知,您实际上希望您的 ActionDef
别名匹配任何采用 Prompter
任何类型的函数,即 Prompter[Any]
。在这种情况下,您可以将其定义为:
ActionDef = Callable[[Prompter[Any]],None]
# or,if you're using mypy:
# ActionDef = Callable[[Prompter],None]
# Now `ActionDef` is no longer generic.
ACTION_DEFS: List[ActionDef] = []