基于Pythontyping模块的类型标注
- 开源代码
- 2025-09-05 00:36:02

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.UnionUnion[X, Y] 等价于 X | Y ,意味着满足 X 或 Y 之一。
typing.Optional : 可选Optional[X] 等价于 X | None (或 Union[X, None] )。
相关链接docs.python.org/zh-cn/3.13/library/typing.html#
基于Pythontyping模块的类型标注由讯客互联开源代码栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“基于Pythontyping模块的类型标注”
上一篇
VMware安装教程