Mypy type of concatenate tuples

Question:

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.

Asked By: mpaskov

||

Answers:

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.

Answered By: chepner

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
Answered By: Eugene Yarmash

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)
Answered By: anthony sottile
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.