CodeRoadMap
首页路线题库资源库文章社区
CodeRoadMap

程序员的学习成长路线图。内容免费开放,登录后可同步路线图与课时进度。

由 程序员柏风 独立维护 · 关于作者

学习

  • 路线图
  • 课程
  • 面试题
  • 文章
  • 我

更多

  • 资源
  • 社区
  • 关于作者
  • 内容说明

© 2026 CodeRoadMap

津ICP备2026012044号-1·津公网安备12011002026155号·coderoadmap@126.com
Python 进阶/课时/静态类型与校验
RawBlame
课时目录12 节

Python 进阶

  1. 01Python 进阶地图
  2. 02类型与数据结构
  3. 03OOP 深入
  4. 04函数式特性
  5. 05并发与异步
  6. 06Web 框架
  7. 07包管理与虚拟环境
  8. 08静态类型与校验
  9. 09测试框架
  10. 10代码质量工具
  11. 11算法与数据结构
  12. 12综合练习

静态类型与校验

mypy、pyright、pydantic、static-typing。

30 分钟

类型系统进阶

Python 3.10+ 的类型注解已足够表达大多数 API 契约;配合 mypy / pyright 可在运行前发现错误。基础见 python-fundamentals;Pydantic 与 Agent schema 见 ai-agents-essentials;/roadmaps/python。

学习目标

  • 使用 X | Y、list[str]、TypedDict、Protocol
  • 编写泛型函数与 TypeVar 约束
  • 配置 mypy 并对模块做静态检查

现代注解语法

from typing import TypedDict, Protocol, TypeVar

class LessonMeta(TypedDict):
    slug: str
    title: str
    published: bool

def slugify(title: str) -> str:
    return title.lower().replace(" ", "-")

T = TypeVar("T")

def first(items: list[T]) -> T | None:
    return items[0] if items else None

Protocol(结构化子类型)

class SupportsRender(Protocol):
    def render(self, source: str) -> str: ...

def publish(renderer: SupportsRender, md: str) -> str:
    return renderer.render(md)

class Plain:
    def render(self, source: str) -> str:
        return source.strip()

# Plain 无需继承 SupportsRender,只要有 render 方法即可
publish(Plain(), "# Hello")

mypy 配置片段

# pyproject.toml
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
mypy src/

常见修复:# type: ignore[code] 仅作最后手段,优先改类型或重构。

与运行时校验

工具阶段用途
mypy静态开发期类型错误
Pydantic运行时HTTP/API 边界校验
isinstance运行时窄化 Union

FastAPI 的 response_model 同时受益于两者。

练习

  • 为 count_chars 函数(packaging 课)补全返回类型 dict[str, int]
  • 定义 LessonRepo Protocol,含 get(slug: str) -> LessonMeta | None
  • 对一个小模块运行 mypy,修复至少一处报错

小结

typing 是文档 + 自动检查,不替代测试。 下一课 pytest 覆盖行为正确性,与静态类型形成双保险。

加载本节练习…
← 上一课包管理与虚拟环境下一课 →测试框架