类型提示(PEP 484+)让你为变量、函数参数和返回值标注预期的类型。它们是可选的且在运行时不被强制执行——Python 运行时会忽略它们——但它们能够启用静态分析、更好的工具支持和更清晰的代码。
基本语法
python
() -> :
name * times
age: =
names: [] = [, ]
scores: [, ] = {: }
: type 用来标注参数/变量,-> type 标注返回值。这些文档化了意图并被工具检查,但 Python 不会在运行时强制执行它们(传递错误的类型不会自动抛出异常)。
from typing import Optional, Union, Callable, Any
def find(id: int) -> Optional[str]: # str OR None (= str | None in 3.10+)
...
x: int | str # Union (3.10+ syntax)
handler: Callable[[int], bool] # a function taking int, returning bool
items: list[dict[str, int]] # nested generics
def add(a: int, b: int) -> int:
return a + b
add("hello", 3) # ✅ Python runs it (and crashes); ❌ mypy/pyright flags it BEFORE running
像 mypy 或 pyright 这样的类型检查器分析提示并在你运行代码之前报告类型错误——捕获整个类别的 bug(错误的参数类型、None 的误用),就像编译器一样。
✓ Catch type bugs early via static checkers (mypy, pyright) — before runtime
✓ IDE support — better autocomplete, refactoring, inline error detection
✓ Self-documenting code — signatures show exactly what's expected/returned
✓ Powers frameworks — FastAPI/Pydantic USE hints for validation & docs
✓ Easier maintenance of large codebases (catch breaking changes)
You can add hints incrementally — a few functions, or strictly everywhere.
Unannotated code still works. "Gradual typing" suits adopting them over time.
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int # Pydantic USES the hint to VALIDATE data at runtime
User(name="Ann", age="x") # raises a validation error
某些库(Pydantic、FastAPI)读取类型提示来验证数据和生成文档——使它们在运行时具有功能意义。
类型提示将静态类型的许多好处带给 Python,而不会牺牲其动态灵活性:它们通过 mypy/pyright 早期捕获类型相关的 bug、显著改善 IDE 工具和重构、充当实时文档,并赋能现代框架(FastAPI、Pydantic)使用它们进行验证和自动生成文档。
虽然是可选的且不被 Python 本身在运行时强制执行,但它们已成为专业和大规模 Python 代码库中的标准做法,因为它们使代码更加可靠、可维护和自我说明——越来越成为一种预期的实践,特别是随着项目规模的增长。