
关于
高效使用 Python 类型提示,涵盖 TypeVar、Generic、Protocol、TypedDict 和 Pydantic 运行时验证。
Python 类型标注模式
现代类型标注,用于安全、文档化的 Python 代码。
基本注解
name: str = "Alice"
count: int = 42
items: list[str] = ["a", "b"]
mapping: dict[str, int] = {"key": 1}
def greet(name: str, times: int = 1) -> str:
return f"Hello, {name}!" * times
def find(id: int) -> str | None:
return db.get(id)
集合
from collections.abc import Sequence, Mapping, Iterable
def process(items: Sequence[str]) -> list[str]:
return [item.upper() for item in items]
def lookup(data: Mapping[str, int], key: str) -> int:
return data.get(key, 0)
Matrix = list[list[float]]
Config = dict[str, str | int | bool]
Optional 和 Union
def find(id: int) -> User | None:
pass
def parse(value: str | int | float) -> str:
pass
def fetch(url: str, timeout: float | None = None) -> bytes:
pass
TypedDict
from typing import TypedDict, Required, NotRequired
class UserDict(TypedDict):
id: int
name: str
email: str | None
class APIResponse(TypedDict):
data: Required[list[dict]]
error: NotRequired[str]
Callable
from collections.abc import Callable
Handler = Callable[[str, int], bool]
from typing import Protocol
class Processor(Protocol):
def __call__(self, data: str, *, verbose: bool = False) -> int: ...
泛型
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T | None:
return items[0] if items else None
Protocol(结构化类型)
from typing import Protocol
class Readable(Protocol):
def read(self, n: int = -1) -> bytes: ...
def load(source: Readable) -> dict:
data = source.read()
return json.loads(data)
类型守卫
from typing import TypeGuard
def is_string_list(val: list[object]) -> TypeGuard[list[str]]:
return all(isinstance(x, str) for x in val)
Literal 和 Final
from typing import Literal, Final
Mode = Literal["read", "write", "append"]
MAX_SIZE: Final = 1024
快速参考
| 类型 | 用例 | |------|------| | X or None | 可选值 | | list[T] | 同质列表 | | dict[K, V] | 字典 | | Callable[[Args], Ret] | 函数类型 | | TypeVar("T") | 泛型参数 | | Protocol | 结构化类型 | | TypedDict | 固定键的字典 | | Literal["a", "b"] | 仅特定值 | | Final | 不可重新赋值 |
类型检查器命令
uv run mypy src/ --strict
uv run pyright src/
知识参考
Python 3.10+、typing、TypeVar、Generic、Protocol、mypy、pyright、TypedDict、Literal、Final
兼容工具
Claude CodeCursorGitHub Copilot
标签
后端开发

