当解包元组时,是否可以使用类型提示?我想这样做,但结果会导致SyntaxError
:
from typing import Tuple
t: Tuple[int, int] = (1, 2)
a: int, b: int = t
# ^ SyntaxError: invalid syntax
当解包元组时,是否可以使用类型提示?我想这样做,但结果会导致SyntaxError
:
from typing import Tuple
t: Tuple[int, int] = (1, 2)
a: int, b: int = t
# ^ SyntaxError: invalid syntax
a
时会出现这种情况,你确定你没有这样做吗? - joela = int(a)
或其他重新赋值操作,就会出现这种情况。如果您使用 mypy 进行静态类型检查,请使用 --allow-redefinition
来避免警告。 - normaniustyping.cast
函数来类型提示解包操作。t: tuple[int, int] = (1, 2)
a, b = t
# type hint of a -> Literal[1]
# type hint of b -> Literal[2]
使用cast(new_type, old_type)
,你可以将那些丑陋的文本转换为整数。
from typing import cast
a, b = cast(tuple[int, int], t)
# type hint of a -> int
# type hint of b -> int
当使用Numpy NDArrays中的未知类型
时,这可能会很有用。
# type hint of arr -> ndarray[Unknown, Unknown]
a, b = cast(tuple[float, float], arr[i, j, :2]
# type hint of a -> float
# type hint of b -> float
def f() -> Tuple[int, int]: return 1, 2
,并且我的解包a, b = f()
都想要a: float
和b: float
。 - Caia
和b
都将包含整数。 - Jeyekomona
和b
应该是浮点数,并且稍后将包含浮点数,则无论哪个函数给出其初始值或提示是什么,我都希望将它们提示为浮点数。 - Caia, b = (float(x) for x in f())
。 - Jeyekomon