Python 变长泛型类型

标签 python python-3.x python-typing

是否可以创建访问可变长度参数类型的泛型类型?

基本上,我正在尝试创建一个通用的 observable,用户可以在其中定义他们想要使用类型提示接受的参数。

前任:

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)

最佳答案

据我所知,no . But they plan to add itis working on it .
报价:

PEP 484 introduced TypeVar, enabling creation of generics parameterised with a single type. In this PEP, we introduce TypeVarTuple, enabling parameterisation with an arbitrary number of types - that is, a variadic type variable, enabling variadic generics. This enables a wide variety of use cases. In particular, it allows the type of array-like structures in numerical computing libraries such as NumPy and TensorFlow to be parameterised with the array shape, enabling static type checkers to catch shape-related bugs in code that uses these libraries.

关于Python 变长泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60802994/

相关文章:

python - 可以在 python 中向量化这个数组操作吗?

python - 通过实现 __get__ 描述符编写瘦对象代理

python - 如何将字符串转换为纯文本?

python - 比较没有关键重要性的字典的嵌套值

python - 向 JSON 对象 Hook 添加类型提示的正确方法

python - 为什么类型的 Union 不能解析为 Python 中的受约束泛型类型?

python - 尝试覆盖 QTreeView.edit() 时出现最大递归错误

json - 将文本转换为 python 列表

python - 范围内所有子函数中的重载函数

python - 在具有泛型类型的类中定义的数据类的类型提示