Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Hint: same variable length tuples for input and output

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

like image 519
Inspi Avatar asked May 29 '26 00:05

Inspi


1 Answers

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]
like image 124
Mabus Avatar answered May 31 '26 14:05

Mabus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!