Let's say I have a function as follow:
from typing import Tuple
def add_one(numbers: Tuple[int, ...]) -> Tuple[int, ...]:
return tuple(number+1 for number in numbers)
This function takes a Tuple of variable length as an input, and returns another Tuple with the same length.
My questions is: how can I express this with type hints ? As you can see in my example, I was only able to express that both input and output tuples had variable length, not that they have the same.
Edit: this is a dummy example that I used to explain what I meant, while I wouldn't implement it this way IRL, I got a much more complex function that would justify the need for this kind of type hint
Use TypeVar:
from typing import Tuple, TypeVar
TupleType = TypeVar("TupleType", bound=Tuple[int, ...])
def add_one(numbers: TupleType) -> TupleType:
return tuple(number+1 for number in numbers) # type: ignore[return-value]
a = add_one((1, 2, 3))
reveal_type(a)
It shows:
Revealed type is "Tuple[builtins.int, builtins.int, builtins.int]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With