python---类型别名
文章目录
- 基本用法
- 现代 Python (3.10+) 语法
- 应用场景
- 1、简化复杂类型
- 2、提高可读性
- 3、文档化代码
- 注意事项
类型别名是 Python 类型注解系统中用来为复杂类型创建简化的替代名称的功能。它们可以提高代码的可读性和可维护性。
基本用法
1、基本类型别名
MyInt = int
MyStr = str
MyList = list
2、使用 TypeAlias 和 typing 模块来定义类型别名:
from typing import TypeAlias, List, Dict# 简单别名
UserId: TypeAlias = int# 复杂类型别名
UserDict: TypeAlias = Dict[str, str]
NamesList: TypeAlias = List[str]
现代 Python (3.10+) 语法
Python 3.10 引入了更简洁的语法:
# Python 3.10+ 的简化语法
type UserId = int
type UserDict = dict[str, str]
type NamesList = list[str]
type Coordinate = tuple[float, float]
应用场景
1、简化复杂类型
from typing import Union
type JsonValue = Union[str, int, float, bool, None, list[‘JsonValue’], dict[str, ‘JsonValue’]]
2、提高可读性
type Point = tuple[float, float]
def distance(p1: Point, p2: Point) -> float:
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5
3、文档化代码
type CustomerID = int # 表示客户唯一标识符
type OrderID = int # 表示订单唯一标识符
注意事项
1、类型别名不会创建新类型,只是为现有类型提供别名
2、类型别名在运行时会被擦除,仅用于静态类型检查
3、可以使用字符串字面量来前向引用尚未定义的类型