Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 877
Matthewj Avatar asked Jul 31 '26 06:07

Matthewj


1 Answers

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.

like image 87
ThatXliner Avatar answered Aug 02 '26 20:08

ThatXliner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!