Setting the correct type for an empty tuple that later becomes a tuple of a specific type

Viewed 197

I have a python function that looks as following:

from typing import Tuple

def test() -> Tuple[int]:
    o: Tuple[int] = ()
    for i in range(2):
        o+=(i,)
    return o

Evaluating this with mypy returns the errors

error: Incompatible types in assignment (expression has type "Tuple[]", variable has type "Tuple[int]")
error: Incompatible types in assignment (expression has type "Tuple[int, int]", variable has type "Tuple[int]")

Assigning the tuple and return value the type Tuple without the int specification resolves this problem. I would like to specify the contents of the tuple as well though. How can I achieve this?

2 Answers

With regard to type hints, Tuple is not like List.

Tuple[int] means "a tuple of 1 int"

Tuple[int, int] means "a tuple of 2 ints"

List[int] means "a list of ints"

Related