Python 类型提示 Type Hint
Python 3.5+ 支持类型提示,让代码更易维护。
1. 基本类型
def greet(name: str) -> str:
return f"Hello, {name}"
def add(a: int, b: int) -> int:
return a + b
2. 变量类型
# Python 3.6+
name: str = "Alice"
age: int = 25
scores: list = [1, 2, 3]
3. 复杂类型
from typing import List, Dict, Tuple, Optional, Union
# 列表
names: List[str] = ["Alice", "Bob"]
# 字典
scores: Dict[str, int] = {"Alice": 90}
# 可选
age: Optional[int] = None
# 联合类型
value: Union[int, str] = 10
4. 类型别名
User = Dict[str, Union[str, int]]
users: List[User] = []
5. 运行检查
# 安装 mypy
# pip install mypy
# 运行检查
# mypy your_file.py
类型提示让代码更可靠。