我有一个接受特定元组和连接的函数,我试图指定输出的类型,但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]")我猜这是真的,但更通用,因为我指定了我的输入。
发布于 2019-02-09 00:00:44
这是一个known issue,但似乎没有时间表来支持mypy进行正确的类型推断。
发布于 2019-02-09 00:10:46
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发布于 2019-02-09 00:28:49
下面是一个不太冗长的解决方法(python3.5+):
from typing import Tuple
def f(a: Tuple[str, str], b: Tuple[int, int]) -> Tuple[str, str, int, int]:
return (*a, *b)https://stackoverflow.com/questions/54595866
复制相似问题