mpaskov
mpaskov

Reputation: 1264

Mypy type of concatenate tuples

I have a function that takes specific tuples and concatenates and I am trying to specify the type of the output but mypy does not agree with me.

File test.py:

from typing import Tuple

def test(a: Tuple[str, str], b: Tuple[int, int]) -> Tuple[str, str, int, int]:
    return a + b

running mypy 0.641 as mypy --ignore-missing-imports test.py I get:

test.py:5: error: Incompatible return value type (got "Tuple[Any, ...]", expected "Tuple[str, str, int, int]")

Which i guess is true but more generic, given that I specify my inputs.

Upvotes: 5

Views: 1609

Answers (3)

chepner
chepner

Reputation: 531165

This is was a known issue, but there appears to be no timeline for enabling mypywas fixed later in 2019 to do the correct type inference.

Upvotes: 7

Eugene Yarmash
Eugene Yarmash

Reputation: 149796

Concatenation of fixed-length tuples is not currently supported by mypy. As a workaround, you can construct a tuple from individual elements:

from typing import Tuple

def test(a: Tuple[str, str], b: Tuple[int, int]) -> Tuple[str, str, int, int]:
    return a[0], a[1], b[0], b[1]

or using unpacking if you have Python 3.5+:

def test(a: Tuple[str, str], b: Tuple[int, int]) -> Tuple[str, str, int, int]:
    return (*a, *b)  # the parentheses are required here

Upvotes: 1

anthony sottile
anthony sottile

Reputation: 69914

Here is a less-verbose workaround (python3.5+):

from typing import Tuple

def f(a: Tuple[str, str], b: Tuple[int, int]) -> Tuple[str, str, int, int]:
    return (*a, *b)

Upvotes: 0

Related Questions