Python中的类型注解与类型提示
字数 688 2025-11-05 08:31:58
Python中的类型注解与类型提示
描述
类型注解(Type Annotations)是 Python 3.5 引入的特性,允许开发者为变量、函数参数和返回值等添加类型信息。类型提示(Type Hints)则是基于注解的静态类型检查实践,通过工具(如 mypy)在代码运行前检测类型错误,提升代码可读性和健壮性。
1. 基本语法与用途
-
变量注解:直接为变量标注类型。
name: str = "Alice" age: int = 30注解不会影响运行时行为,但IDE和类型检查工具会利用这些信息。
-
函数注解:定义参数和返回值的类型。
def greet(name: str) -> str: return f"Hello, {name}"箭头
->后是返回值类型,函数体本身无需修改。
2. 复杂类型与容器注解
对于列表、字典等容器,需使用 typing 模块(Python 3.9+ 可直接用内置类型):
from typing import List, Dict, Optional
# 注解列表和字典
def process_data(items: List[int], mapping: Dict[str, int]) -> None:
pass
# 可选类型(可能为None)
def find_user(id: int) -> Optional[str]:
...
Python 3.9+ 简化写法:
def process_data(items: list[int], mapping: dict[str, int]) -> None:
pass
3. 类型别名与自定义类型
-
类型别名:简化复杂注解。
from typing import Dict, Tuple # 别名示例 Coordinate = Tuple[float, float] UserMap = Dict[int, str] def locate(point: Coordinate) -> UserMap: ... -
自定义类型:使用
NewType或TypeAlias(Python 3.10+)。from typing import NewType UserId = NewType('UserId', int) id = UserId(1001) # 运行时仍是int,但类型检查时区分
4. 联合类型与字面量类型
-
联合类型:允许多种类型。
from typing import Union def display(value: Union[int, str]) -> None: print(value) # Python 3.10+ 可用 | 运算符 def display_v2(value: int | str) -> None: ... -
字面量类型:限制为特定值。
from typing import Literal def set_direction(direction: Literal["left", "right"]) -> None: ...
5. 类型检查工具的使用
安装 mypy 并检查代码:
pip install mypy
mypy your_script.py
示例:
# 示例代码(存为test.py)
def add(a: int, b: int) -> int:
return a + b
result = add(1, "2") # 类型错误!
运行 mypy test.py 会报错:
test.py:4: error: Argument 2 to "add" has incompatible type "str"; expected "int"
6. 高级特性:泛型与协议
-
泛型:使函数或类支持多种类型。
from typing import TypeVar, List T = TypeVar('T') def first_item(items: List[T]) -> T: return items[0] -
协议:结构化类型(鸭子类型的静态检查)。
from typing import Protocol class Renderable(Protocol): def render(self) -> str: ... def render_item(item: Renderable) -> None: print(item.render())
总结
类型注解通过明确类型约束,结合工具(如 mypy)提前发现错误,尤其适用于大型项目。但需注意:
- 注解仅是提示,不影响运行时;
- 渐进式采用,可逐步添加注解;
- 灵活使用
Any类型绕过检查(但应谨慎)。