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)
Note: This feature was added in Python 3.11
As far as I know, no. But they plan to add it and is working on it.
To quote:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With