打开元组时输入提示?

Cai*_*Cai 15 type-hinting python-3.x

拆开元组时可以使用类型提示吗?我想这样做,但结果是SyntaxError

from typing import Tuple

t: Tuple[int, int] = (1, 2)
a: int, b: int = t
#     ^ SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

Pat*_*ugh 16

根据PEP-0526,您应该先注释类型,然后再解压缩

a: int
b: int
a, b = t
Run Code Online (Sandbox Code Playgroud)

  • 这是可悲的,<variable>:<typehint> 到底怎么不能使用任何语法上下文,其中变量赋值是合法的...... (10认同)
  • 哈哈,我什至不知道您可以输入提示作为自己的声明! (4认同)
  • 仍会触发警告:未使用时重新声明了上面定义的“ a” (3认同)

Jor*_*mez 11

就我而言,我使用该typing.cast函数来键入提示解包操作。

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

# type hint of a -> Literal[1]
# type hint of b -> Literal[2]
Run Code Online (Sandbox Code Playgroud)

通过使用,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
Run Code Online (Sandbox Code Playgroud)

Unknown这在使用具有类型的Numpy NDArray 时非常有用

# 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
Run Code Online (Sandbox Code Playgroud)