Skip to content
Advertisement

Can the * (unpacking) operator be typed in Python? Or any other variadic args function such that all variadic types are in the result type?

Working with type stubs, I’m wondering if it’s possible to express a type in Python that allows you to type this correctly for any number of arguments:

JavaScript

At first glance, I came with:

JavaScript

But this of course will only type correctly the first T.

Is the only possible way to write the overrides for all arities?

JavaScript

This is not complete either, since it does not carry enough type information to type something like:

JavaScript

Advertisement

Answer

This can solved through TypeVarTuple from PEP646, implemented in Python 3.11 or forward compat module typing-extensions.

See this analog example:

JavaScript

Also see Dynamic TypeVar for a sequence of types for a solution.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement