欢迎来到 mypy 文档!¶
Mypy 是一个用于 Python 的静态类型检查器。
类型检查器帮助确保您在代码中正确使用变量和函数。通过 mypy,您可以为 Python 程序添加类型提示(PEP 484),当您不正确地使用这些类型时,mypy 将发出警告。
Python 是一种动态语言,因此通常只有在尝试运行代码时才能看到错误。Mypy 是一个 静态 检查器,因此它能够在不运行程序的情况下发现程序中的错误!
这里有一个小例子来激发您的兴趣:
number = input("你最喜欢的数字是什么?")
print("它是", number + 1) # 错误:不支持的操作数类型用于 + ("str" 和 "int")
为 mypy 添加类型提示不会干扰程序的运行方式。可以将类型提示视为类似于注释!即使 mypy 报告错误,您仍然可以使用 Python 解释器运行代码。
Mypy 的设计考虑到了渐进式类型。这意味着您可以逐步为代码库添加类型提示,并且在静态类型不方便时,您始终可以回退到动态类型。
Mypy 具有强大且易于使用的类型系统,支持类型推断、泛型、可调用类型、元组类型、联合类型、结构性子类型等功能。使用 mypy 将使您的程序更易于理解、调试和维护。
备注
尽管 mypy 已经准备好用于生产,但偶尔可能会有更改导致向后兼容性中断。mypy 开发团队会尽量减少对用户代码的影响。如果出现重大向后不兼容的更改,mypy 的主要版本号将被提高。
内容¶
第一步
类型系统参考
配置和运行 mypy
- 运行 mypy 和管理导入(imports)
- mypy命令行(command line)
- 指定类型检查的内容(what to type check)
- 可选参数(arguments)
- 配置文件(Config file)
- 导入发现(Import discovery)
- 平台配置(Platform configuration)
- 禁止动态类型(Disallow dynamic typing)
- 未类型化的定义和调用(Untyped definitions and calls)
- None 和 Optional 处理(None and Optional handling)
- 配置警告(Configuring warnings)
- 其他严格性标志(Miscellaneous strictness flags)
- 配置错误消息(Configuring error messages)
- 增量模式(Incremental mode)
- 高级选项(Advanced options)
- 报告生成(Report generation)
- 启用不完整/实验性功能(Enabling incomplete/experimental features)
- 杂项(Miscellaneous)
- mypy 配置文件(mypy configuration file)
- 配置文件格式(Config file format)
- 单个模块和全局选项(Per-module and global options)
- 反转选项值(Inverting option values)
mypy.ini
示例 (Example)- 导入发现(Import discovery)
- 平台配置(Platform configuration)
- 禁止动态类型(Disallow dynamic typing)
- 未类型定义和调用(Untyped definitions and calls)
- None 和 Optional 处理(None and Optional handling)
- 配置警告(Configuring warnings)
- 抑制错误(Suppressing errors)
- 其他严格性标志(Miscellaneous strictness flags)
- 配置错误消息(Configuring error messages)
- 增量模式(Incremental mode)
- 高级选项(Advanced options)
- 报告生成(Report generation)
- 其他(Miscellaneous)
- 使用 pyproject.toml 文件(Using a pyproject.toml file)
- pyproject.toml 示例(Example)
- 内联配置(Inline configuration)
- Mypy 守护进程 (mypy 服务)
- 使用已安装的包(Using installed packages)
- 扩展和集成 mypy(Extending and integrating mypy)
- 自动存根生成(Automatic stub generation) (stubgen)
- 自动化存根测试(Automatic stub testing)(stubtest)
其他
- 常见问题及解决方案(Common issues and solutions)
- 明显错误的代码未报告错误(No errors reported for obviously wrong code)
- 冗余错误与局部静默检查器(Spurious errors and locally silencing the checker)
- 忽略整个文件(Ignoring a whole file)
- 运行时代码问题(Issues with code at runtime)
- Mypy 运行速度慢(Mypy runs are slow)
- 空集合的类型(Types of empty collections)
- 不兼容类型的重新定义(Redefinitions with incompatible types)
- 不变性与协变性(Invariance vs covariance)
- 将超类型声明为变量类型(Declaring a supertype as variable type)
- 复杂的类型测试(Complex type tests)
- Python 版本和系统平台检查(Python version and system platform checks)
- 显示表达式的类型(Displaying the type of an expression)
- 静默代码检查工具(Silencing linters)
- 可变协议成员的协变子类型被拒绝(Covariant subtyping of mutable protocol members is rejected)
- 处理冲突的名称(Dealing with conflicting names)
- 使用开发版 mypy(Using a development mypy build)
- 变量与类型别名(Variables vs type aliases)
- 不兼容的重写(Incompatible overrides)
- 不可达代码(Unreachable code)
- 缩小范围和内部函数(Narrowing and inner functions)
- 支持的 Python 特性(Supported Python features)
- 错误代码(Error codes)
- 默认启用的错误代码(Error codes enabled by default)
- 检查属性是否存在 [attr-defined]
- 检查每个联合项中属性是否存在 [union-attr]
- 检查名称是否定义 [name-defined]
- 检查变量在定义之前是否被使用 [used-before-def]
- 检查调用中的参数 [call-arg]
- 检查参数类型 [arg-type]
- 检查对重载函数的调用 [call-overload]
- 检查类型的有效性 [valid-type]
- 当变量类型不明确时要求注解 [var-annotated]
- 检查重写的有效性 [override]
- 检查函数是否返回值 [return]
- 检查函数的主体不为空 [empty-body]
- 检查返回值是否兼容 [return-value]
- 检查赋值语句中的类型 [assignment]
- 检查赋值目标是否为方法 [method-assign]
- 检查类型变量值 [type-var]
- 检查各种运算符的使用 [operator]
- 检查索引操作 [index]
- 检查列表项 [list-item]
- 检查字典项 [dict-item]
- 检查 TypedDict 项 [typeddict-item]
- 检查 TypedDict 键 [typeddict-unknown-key]
- 检查目标的类型是否已知 [has-type]
- 检查导入问题 [import]
- 检查导入目标是否可以找到 [import-not-found]
- 检查导入目标是否可以找到 [import-untyped]
- 检查每个名称是否仅定义一次 [no-redef]
- 检查被调用函数是否返回值 [func-returns-value]
- 检查抽象类的实例化 [abstract]
- 安全处理抽象类型对象类型 [type-abstract]
- 检查通过 super 调用抽象方法是否有效 [safe-super]
- 检查 NewType 的目标 [valid-newtype]
- 检查 __exit__ 的返回类型 [exit-return]
- 检查命名的一致性 [name-match]
- 检查字面量在预期位置的使用 [literal-required]
- 检查重载函数是否有实现 [no-overload-impl]
- 检查协程返回值是否被使用 [unused-coroutine]
- 关于顶层 await 表达式发出警告 [top-level-await]
- 关于在协程外使用 await 表达式发出警告 [await-not-async]
- 检查 assert_type 中的类型 [assert-type]
- 检查函数未在布尔上下文中使用 [truthy-function]
- 检查字符串格式化/插值是否类型安全 [str-format]
- 检查隐式字节强制转换 [str-bytes-safe]
- 检查重载函数是否重叠 [overload-overlap]
- 检查无法匹配的重载签名 [overload-cannot-match]
- 通知未检查函数中的注释 [annotation-unchecked]
- 装饰器在属性之前不支持 [prop-decorator]
- 报告语法错误 [syntax]
- 只读 TypedDict 的键被修改 [typeddict-readonly-mutated]
- 杂项检查 [misc]
- 可选检查的错误代码(Error codes for optional checks)
- 检查类型参数是否存在 [type-arg]
- 检查每个函数是否有注释 [no-untyped-def]
- 检查类型转换是否冗余 [redundant-cast]
- 检查方法是否具有冗余的 Self 注解 [redundant-self]
- 检查比较是否重叠 [comparison-overlap]
- 检查未注解的函数未被调用 [no-untyped-call]
- 检查函数不返回 Any 值 [no-any-return]
- 检查由于缺少导入而没有 Any 组件的类型 [no-any-unimported]
- 检查语句或表达式是否不可达 [unreachable]
- 检查导入或使用的特性是否已弃用 [deprecated]
- 检查表达式是否冗余 [redundant-expr]
- 警告有关仅在某些执行路径中定义的变量 [possibly-undefined]
- 检查表达式在布尔上下文中不隐式为真 [truthy-bool]
- 检查可迭代对象在布尔上下文中不隐式为真 [truthy-iterable]
- 检查
# type: ignore
是否包含错误代码 [ignore-without-code] - 检查可等待返回值是否被使用 [unused-awaitable]
- 检查
# type: ignore
注释是否被使用 [unused-ignore] - 检查在重写基类方法时是否使用
@override
[explicit-override] - 检查可变属性的重写是否安全 [mutable-override]
- 检查
reveal_type
是否从 typing 或 typing_extensions 导入 [unimported-reveal] - 检查
TypeIs
是否缩小类型 [narrowed-type-not-subtype]
- 附加功能(Additional features)
- 常见问题解答(Frequently Asked Questions)
- 为什么同时有动态和静态类型?(Why have both dynamic and static typing?)
- 我的项目会受益于静态类型吗?(Would my project benefit from static typing?)
- 我可以使用 mypy 来检查我现有的 Python 代码吗?(Can I use mypy to type check my existing Python code?)
- 静态类型会使我的程序运行得更快吗?(Will static typing make my programs run faster)
- mypy 是免费的吗?(Is mypy free?)
- 我可以在 mypy 中使用鸭子类型吗?(Can I use duck typing with mypy?)
- 我喜欢 Python,但我不需要静态类型(I like Python and I have no need for static typing)
- mypy 程序与普通 Python 程序有什么不同?(How are mypy programs different from normal Python?)
- mypy 与 Cython 有什么不同?(How is mypy different from Cython?)
- 它在 PyPy 上运行吗?(Does it run on PyPy?)
- mypy 是一个很棒的项目。我可以帮助吗?(Mypy is a cool project. Can I help?)
- Mypy 版本说明