解压缩元组时的类型提示?

在解压缩元组时可以使用类型提示吗?我想这样做,但它的结果是 SyntaxError:

from typing import Tuple


t: Tuple[int, int] = (1, 2)
a: int, b: int = t
#     ^ SyntaxError: invalid syntax
16086 次浏览

According to PEP-0526, you should annotate the types first, then do the unpacking

a: int
b: int
a, b = t

In my case i use the typing.cast function to type hint an unpack operation.

t: tuple[int, int] = (1, 2)
a, b = t


# type hint of a -> Literal[1]
# type hint of b -> Literal[2]

By using the cast(new_type, old_type) you can cast those ugly literals into integers.

from typing import cast


a, b = cast(tuple[int, int], t)


# type hint of a -> int
# type hint of b -> int

This can be useful while working with Numpy NDArrays with Unknown types

# 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