【发布时间】:2021-08-27 08:29:20
【问题描述】:
考虑以下代码:
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:如何定义写ACTION_DEFS打字声明?
问题2(标题来自哪里):有没有办法定义Prompter,这样我就不需要随身携带[_T]?
【问题讨论】:
标签: python function generics type-hinting pylance