I’m looking for a way to define a type alias MyAlias such that MyAlias[T1, T2, T3] is equivalent to list[T1] | list[T2] | list[T3], but where the number of type parameters of MyAlias is variadic (not just 3 as in this example). I need this to be recognizable by mypy.
Is it possible to do it in Python? If not, do you know if such feature is planned?
One of my attempts was to define a recursive type, but this unfortunately doesn’t work:
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
type MyAlias[T, *Ts] = list[T] | MyAlias[*Ts]
# error: Invalid recursive alias: a union item of itself [misc]
# error: TypeVarTuple cannot be split [type-arg]
Has been discussed a few times. Probably needs a champion to push this proposal to a full PEP that can be accepted. This is not that controversial AFAIK.
There’s other related background that was less positively received, and despite the theoretical simplicity, the reality of how current python type checkers were handling it at the time was… not ideal.
If someone else wants to pick it up, they should look at the (prior?) existing support for it in pyright which was (is?) behind an experimental feature flag to satisfy the requirement that a type checker implement it.
I can put it on a todo list for the new year if nobody wants to draft something up before then, but I don’t think I should be adding another thing to my own short-term list right now.