1

考虑以下代码:

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]] = []

我从 pylance 收到错误消息List[ActionDef[_T]]

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:如何定义写ACTION_DEFS类型声明?

问题2(标题来自哪里):有没有一种方法可以定义Prompter我不需要随身携带的方式[_T]

4

1 回答 1

0

您遇到的第一个错误是因为使用具有泛型类型的类型变量会创建泛型别名,而不是具体类型。您必须使用具体类型注释变量,因此会出现错误。

第二个错误,我认为它是特定于 的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] = []
于 2021-06-21T21:10:12.253 回答