7

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)

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This has been accepted as PEP646 and scheduled for Python 3.11. For < 3.11 the typing_extensions package provides backports. So the TypeVarTuple feature is available right now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.