Overloads with variable-length arguments via *args #5866
-
I'm trying to specify overloads for a function that returns a tuple of the same length as the number of arguments given, while also supporting a variable length tuple return for a *args invocation. Is there any way to make this work? Code sample in pyright playground from typing import overload
@overload
def my_fun(bar1: int, /) -> int: # type error
...
@overload
def my_fun(bar1: int, bar2: int, /) -> tuple[int, int]:
...
@overload
def my_fun(*bar: int) -> tuple[int, ...]:
...
def my_fun(*bar: int,) -> tuple[int, ...] | int:
...
my_iter = (1,2,3)
result = my_fun(*my_iter) Note that in my actual code, the function is also generic on argument and return, so with the lack of higher-kind TypeVar I'm not able to use some kind of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
If I understand your problem correctly, if you pass your function a single @overload
def my_fun(a: int, /) -> int: ...
@overload
def my_fun(a: int, b: int, /, *bar: int) -> tuple[int, int, *tuple[int, ...]]: ...
def my_fun(*bar: int) -> tuple[int, ...] | int: ... |
Beta Was this translation helpful? Give feedback.
You are correct that this isn't possible with the type system today. There has been some discussion of a "Map" mechanism that allows a transform to be applied to each element in a TypeVarTuple, but this hasn't made it to a PEP proposal yet.