【问题标题】:Type hint of generic function?泛型函数的类型提示?
【发布时间】: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


    【解决方案1】:

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

    第二个错误,我假设它特定于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] = []
    

    【讨论】:

      猜你喜欢
      • 2022-10-14
      • 2020-11-06
      • 2021-11-25
      • 2020-10-24
      • 2017-08-18
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多