为稍后成为特定类型元组的空元组设置正确的类型
Setting the correct type for an empty tuple that later becomes a tuple of a specific type
我有一个 python 函数,如下所示:
from typing import Tuple
def test() -> Tuple[int]:
o: Tuple[int] = ()
for i in range(2):
o+=(i,)
return o
用 mypy 评估这个return错误
error: Incompatible types in assignment (expression has type "Tuple[]", variable has type "Tuple[int]")
error: Incompatible types in assignment (expression has type "Tuple[int, int]", variable has type "Tuple[int]")
将元组和 return 值分配给没有 int 规范的元组类型可以解决此问题。不过,我也想指定元组的内容。我怎样才能做到这一点?
# For tuples of variable size, we use one type and ellipsis
x: tuple[int, ...] = (1, 2, 3) # Python 3.9+
x: Tuple[int, ...] = (1, 2, 3)
发件人:
关于类型提示,Tuple
不同于 List
。
Tuple[int]
表示“1 int
中的 tuple
”
Tuple[int, int]
表示“2 int
中的 tuple
”
List[int]
表示“int
中的 list
”
我有一个 python 函数,如下所示:
from typing import Tuple
def test() -> Tuple[int]:
o: Tuple[int] = ()
for i in range(2):
o+=(i,)
return o
用 mypy 评估这个return错误
error: Incompatible types in assignment (expression has type "Tuple[]", variable has type "Tuple[int]")
error: Incompatible types in assignment (expression has type "Tuple[int, int]", variable has type "Tuple[int]")
将元组和 return 值分配给没有 int 规范的元组类型可以解决此问题。不过,我也想指定元组的内容。我怎样才能做到这一点?
# For tuples of variable size, we use one type and ellipsis
x: tuple[int, ...] = (1, 2, 3) # Python 3.9+
x: Tuple[int, ...] = (1, 2, 3)
发件人:
关于类型提示,Tuple
不同于 List
。
Tuple[int]
表示“1 int
中的 tuple
”
Tuple[int, int]
表示“2 int
中的 tuple
”
List[int]
表示“int
中的 list
”