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)
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)
| 归档时间: |
|
| 查看次数: |
1419 次 |
| 最近记录: |