首页 > 解决方案 > Python variable length generics types

问题描述

Is is possible to create a generic type that access a variable length argument types?

Basically, I'm trying to create a generic observable where the user can define which arguments they want to accept with type hints.

Ex:

Types = TypeVar("Types", var_length=True)

class Obserable(Generic[Types]):

    def subscribe(func: Callable[[Types], None]):
        ...

    def notify(*args: Types):
        ...

def callback(arg1: int, arg2: str, arg3: int) -> None:
    ...

observer: Observable[int, str, int] = Observable()
observer.subscribe(callback)
observer.notify(1, "hello", 5)

标签: pythonpython-3.xpython-typing

解决方案


据我所知,没有但他们计划添加它正在努力

去引用:

PEP 484 引入了 TypeVar,允许创建使用单一类型参数化的泛型。在这个 PEP 中,我们引入了 TypeVarTuple,支持使用任意数量的类型进行参数化 - 即可变参数类型变量,支持可变参数泛型。这支持了各种各样的用例。特别是,它允许数值计算库(如 NumPy 和 TensorFlow)中的类数组结构类型使用数组形状进行参数化,从而使静态类型检查器能够在使用这些库的代码中捕获与形状相关的错误。


推荐阅读