基于 Python typing 模块的类型标注
Python 是动态类型语言,运行时不强制要求函数与变量类型标注,但是也支持标注类型,以便于类型检查,IDE提示等,提高代码质量。
Python 默认的类型注释比较简单,Python 3.5 新增了 typing 模块,扩展了类型功能。
变量类型标注
age: int = 25
name: str = "张三"
print(age, ' ', name)
函数参数和返回值 类型标注
def hello(name: str) -> str:
return "Hello, " + name
列表类型标注
from typing import List
numbers: list[int] = [1, 2, 3]
# 或
numbers1: List[int] = [1, 2, 3]
字典类型标注
from typing import Dict
user_info: dict[str, str] = {"name": "Alice", "age": "25"}
user_info1: Dict[str, str] = {"name": "Alice", "age": "25"}
元组类型标注
from typing import Tuple
numbers: tuple[int] = (1, 2, 3)
# 或
numbers1: Tuple[int] = (1, 2, 3)
print(type(numbers))
print(type(numbers1))
typing.Union
Union[X, Y]
等价于 X | Y
,意味着满足 X 或 Y 之一。
typing.Optional : 可选
Optional[X]
等价于 X | None
(或 Union[X, None]
)。
相关链接
https://docs.python.org/zh-cn/3.13/library/typing.html#