The Python Oracle

Mypy type of concatenate tuples

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Music Box Puzzles

--

Chapters
00:00 Question
00:48 Accepted answer (Score 5)
01:03 Answer 2 (Score 1)
01:32 Answer 3 (Score 0)
01:49 Thank you

--

Full question
https://stackoverflow.com/questions/5459...

Accepted answer links:
[known issue]: https://github.com/python/mypy/issues/22...

Answer 2 links:
[unpacking]: https://www.python.org/dev/peps/pep-0448/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #mypy

#avk47



ACCEPTED ANSWER

Score 6


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.




ANSWER 2

Score 1


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



ANSWER 3

Score 0


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)