是否可以创建访问可变长度参数类型的泛型类型?
基本上,我正在尝试创建一个通用的 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 it和 is 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/