如何在不激怒 mypy 的情况下将列表转换为元组?

How do I convert a list to a tuple without angering mypy?

我有一个列表(长度为 2),我想将它转换为一个元组

from typing import List, Tuple

l: List[int] = [1, 2]
assert len(l) == 2
t: Tuple[int, int] = tuple(l)

无论我做什么,我都会收到错误消息:

Incompatible types in assignment
(expression has type "Tuple[int, ...]", variable has type "Tuple[int, int]")

我试过拼接

t: Tuple[int, int] = tuple(l)[0:2]
t: Tuple[int, int] = tuple(l[0:2])

并重新创建

t: Tuple[int, int] = tuple([l[0], l[1]])
t: Tuple[int, int] = l[0], l[1]  # strangely invalid syntax, even though t = l[0], l[1] is valid

我已经通读了 the docs,但我还没有找到任何方法来彻底地做到这一点。

不要使用元组函数,使用括号语法。

t: Tuple[int, int] = (l[0], l[1])