CodeWalk

函数注解(Function Annotations)

作者:Yahuda · 2026-05-30 12:55

Python 中函数注解(Function Annotations)的作用是什么?Python 是否强制类型检查?如何使用 typing 模块?

回答

Yahuda

函数注解是元数据,Python 不强制执行类型检查,但可用于类型提示工具(mypy)和文档。

from typing import List, Optional

def process(items: List[int], prefix: str = '') -> Optional[str]:
    # 类型注解只是提示,不强制
    return prefix + str(sum(items)) if items else None

使用场景

  1. 代码可读性和 IDE 自动补全
  2. 静态类型检查(mypy、pyright)
  3. 运行时通过 __annotations__ 访问
print(process.__annotations__)
# {'items': List[int], 'prefix': str, 'return': Optional[str]}

typing 模块提供了复杂类型:Optional, Union, Any, Callable, TypeVar, Generic