Mypy 类型的连接元组
Mypy type of concatenate tuples
我有一个接受特定元组和连接的函数,我正在尝试指定输出类型,但 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 0.641 as mypy --ignore-missing-imports test.py
我得到:
test.py:5: error: Incompatible return value type (got "Tuple[Any, ...]", expected "Tuple[str, str, int, int]")
我猜这是真的,但更通用,因为我指定了我的输入。
这是一个 known issue,但似乎没有启用 mypy
进行正确类型推断的时间表。
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]
或使用 unpacking 如果你有 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
这是一个不太详细的解决方法 (python3.5+):
from typing import Tuple
def f(a: Tuple[str, str], b: Tuple[int, int]) -> Tuple[str, str, int, int]:
return (*a, *b)
我有一个接受特定元组和连接的函数,我正在尝试指定输出类型,但 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 0.641 as mypy --ignore-missing-imports test.py
我得到:
test.py:5: error: Incompatible return value type (got "Tuple[Any, ...]", expected "Tuple[str, str, int, int]")
我猜这是真的,但更通用,因为我指定了我的输入。
这是一个 known issue,但似乎没有启用 mypy
进行正确类型推断的时间表。
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]
或使用 unpacking 如果你有 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
这是一个不太详细的解决方法 (python3.5+):
from typing import Tuple
def f(a: Tuple[str, str], b: Tuple[int, int]) -> Tuple[str, str, int, int]:
return (*a, *b)