Mypy类型的串联元组

时间:2019-02-08 15:44:34

标签: python mypy

我有一个接受特定元组和连接的函数,我试图指定输出的类型,但是mypy与我不同意。

文件test.py

from typing import Tuple

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

mypy --ignore-missing-imports test.py的身份运行mypy 0.641,我得到:

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

鉴于我指定了输入内容,我猜这是对的,但更为笼统。

3 个答案:

答案 0 :(得分:3)

这是一个known issue,但是似乎没有时间表允许OverlayPDF进行正确的类型推断。

答案 1 :(得分:1)

mypy当前不支持固定长度元组的串联。解决方法是,您可以根据各个元素构造一个元组:

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]

,或者如果您使用的是Python 3.5+,则使用unpacking

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

答案 2 :(得分:0)

这是一个不太冗长的解决方法(python3.5 +):

from typing import Tuple

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