Skip to content

ty 1.0 迁移指南:从 mypy 迁移到 ty,解决 type: ignore 不生效的问题

更新于

ty 1.0.0(2026 年 12 月 1 日发布)是 Astral 用 Rust 写的类型检查器。本文在一个 pandas + Pydantic 项目上对照 mypy 2.4.1 实测:为什么 # type: ignore[arg-type] 不再屏蔽任何报错、[tool.mypy] 到 [tool.ty] 的配置对照表、--fix / --add-ignore / baseline 怎么选、只有 warning 也会让 CI 失败的退出码,以及从 beta 升级后的 renamed-rule 警告。

先说结论:ty 1.0.0 于 2026 年 12 月 1 日发布,出自 Astral,也就是做 uv 和 Ruff 的团队。先别动现有配置,把它装在 mypy 旁边跑一遍:

uv add --dev "ty>=1.0,<1.1"
uv run ty check

在已有的 mypy 项目上,第一次运行通常会遇到四件事:

  1. 诊断比 mypy 多。我们的四文件示例从 mypy 的 4 个错误变成 ty 的 8 条诊断。rich 在 mypy --strict 下只有 1 个错误,ty 报了 42 条。
  2. # type: ignore[arg-type] 注释失效。ty 不认方括号里的 mypy 错误码,这些行会重新报错。不带错误码的 # type: ignore 仍然有效。
  3. [tool.mypy] 配置 ty 不读。ignore_missing_imports、disable_error_code 和插件都要换成 [tool.ty] 里的对应写法,对照表见下文。
  4. warning 也会让 CI 失败。只发现 warning 时,ty check 的退出码也是 1。

这些都不需要一次性大改。用 ty check --fix、ty check --add-ignore 和 baseline 文件,就能让老项目通过检查,切换期间 mypy 可以继续跑。

测试范围:标注“实测”的内容都是 2026 年 12 月 2 日在 Apple M4 Max(macOS 26.5)上跑的,环境是 uv 虚拟环境,CPython 3.13、ty 1.0.0、mypy 2.4.1、pandas 3.1.2、pandas-stubs 3.1.0.261029、NumPy 2.5.5 和 Pydantic。Pyright 本身、VS Code 扩展、Django / attrs / pytest 支持、Windows 和 Linux 没有测,这部分内容来自官方文档 (opens in a new tab),文中已注明。引用 Astral 的性能和一致性数据时,会标明是厂商数据。

mypy 到 ty 速查

mypy 里的写法在 ty 里怎么做实测
# type: ignore[arg-type]加上 # ty: ignore[invalid-argument-type](或运行 --add-ignore)是
# type: ignore(不带错误码)不用改,仍然屏蔽整行是
针对某个模块的 ignore_missing_imports = true在 [tool.ty.analysis] 下写 allowed-unresolved-imports = ["pkg.**"]是
disable_error_code = ["..."]在 [tool.ty.rules] 下写 <rule> = "ignore"(规则级别用 "warn" 测过)是
plugins = ["pydantic.mypy"]删掉,Pydantic 支持是内置的是
warn_unused_ignores = true默认开启(unused-type-ignore-comment、unused-ignore-comment)是
check_untyped_defs = true不用改,ty 始终检查没有标注的函数体文档
--strict没有这个参数,另外开启四条规则(见第 6 步)文档
其他 mypy 插件没有对应功能文档
python_version = "3.13"在 [tool.ty.environment] 下写 python-version = "3.13",或者让 ty 读取 requires-python是
热门文章

第 1 步:把 ty 装在 mypy 旁边

ty 在 PyPI 上以单个二进制文件发布。按你平时运行工具的方式选一种:

# as a dev dependency of the project (what we tested)
uv add --dev "ty>=1.0,<1.1"
 
# as a global tool
uv tool install ty@latest
 
# one-off, without installing
uvx ty@1.0.0 check

CI 里要锁定次版本。版本策略 (opens in a new tab)写明,补丁版本包含 bug 修复,而次版本“可能会报告新的类型错误”。用 >=1.0,<1.1 这样的范围,可以避免周一早上的一次发版把流水线变红。

ty 会自己找到运行环境。在 uv 项目里它使用 .venv,并从 pyproject.toml 的 requires-python 读取目标 Python 版本。环境在别的位置时,传 --python path/to/venv。

第 2 步:两个检查器都跑一遍,对比结果

下面是我们用的示例:一个用到 pandas 和 Pydantic 的小型销售报表包,mypy 配置是多数数据项目里常见的样子:

[tool.mypy]
python_version = "3.13"
plugins = ["pydantic.mypy"]
disable_error_code = ["import-untyped"]
warn_unused_ignores = true
 
[[tool.mypy.overrides]]
module = "legacy_vendor.*"
ignore_missing_imports = true

mypy 报 4 个错误:

src/sales_report/models.py:13: error: Argument "dry_run" to "ReportOptions" has incompatible type "str"; expected "bool"  [arg-type]
src/sales_report/report.py:14: error: Argument 1 to "load_orders" has incompatible type "Path"; expected "str"  [arg-type]
src/sales_report/report.py:15: error: Argument "n" to "top_customers" has incompatible type "str"; expected "int"  [arg-type]
src/sales_report/report.py:17: error: Incompatible types in assignment (expression has type "str", variable has type "int")  [assignment]
Found 4 errors in 2 files (checked 4 source files)

ty 不加任何配置,报 8 条(实测)。concise 输出格式每条诊断占一行,方便和 mypy 的结果做 diff:

uv run ty check --output-format concise
src/sales_report/load.py:3:8: error[import-not-found] Cannot resolve imported module `legacy_vendor.client`
src/sales_report/load.py:23:12: error[invalid-explicit-return] Return type does not match returned value: expected `int`, found `int | None`
src/sales_report/load.py:27:12: error[unsupported-operator] Operator `+` is not supported between objects of type `Literal["order-"]` and `int`
src/sales_report/models.py:13:46: error[invalid-argument-type] Argument is incorrect: Expected `bool`, found `Literal["yes"]`
src/sales_report/report.py:14:22: error[invalid-argument-type] Argument to function `load_orders` is incorrect: Expected `str`, found `Path`
src/sales_report/report.py:15:30: error[invalid-argument-type] Argument to function `top_customers` is incorrect: Expected `int`, found `Literal["5"]`
src/sales_report/report.py:17:5: error[invalid-assignment] Object of type `Literal["many"]` is not assignable to attribute `rows` of type `int`
src/sales_report/report.py:19:13: warning[redundant-cast] Value is already of type `int`
Found 8 diagnostics

两边都报的四个错误是同样的 bug,只是换了名字。多出来的四行原因各不相同,分别对应下面的某一步:

ty 多报的诊断mypy 为什么没报解决
legacy_vendor 的 import-not-foundmypy 配了 ignore_missing_imports第 3 步
第 23 行的 invalid-explicit-return这一行有 # type: ignore[return-value]第 4 步
第 27 行的 unsupported-operator这一行有 # type: ignore[operator]第 4 步
redundant-cast 警告mypy 要开 warn_redundant_casts 才报第 5 步

留意 Pydantic 那一行。dry_run 声明为 Field(default=False, strict=True)。同一个模型里还有一个 output: Path 字段,调用时传的是字符串 "./exports"。ty 不用插件、不用配置就报出了 dry_run 的字符串参数,同时接受了 output="./exports"(Pydantic 会把它转成 Path)。mypy 2.4.1 不装插件也会报 dry_run,但会连 output 一起报(实测)。插件的作用就是去掉这类误报,ty 不需要它。

第 3 步:把 [tool.mypy] 翻译成 [tool.ty]

ty 读取 pyproject.toml 里的 [tool.ty],或者单独的 ty.toml,不会读 mypy 或 Pyright 的配置。上面那份配置翻译过来是这样(实测):

[tool.ty.environment]
python-version = "3.13"
 
[tool.ty.analysis]
# mypy: [[tool.mypy.overrides]] module = "legacy_vendor.*", ignore_missing_imports = true
allowed-unresolved-imports = ["legacy_vendor.**"]
 
[tool.ty.rules]
# "ignore" disables a rule, like mypy's disable_error_code
redundant-cast = "warn"
 
# per-directory rule levels, like mypy overrides
[[tool.ty.overrides]]
include = ["tests/**"]
 
[tool.ty.overrides.rules]
invalid-argument-type = "warn"

有几处差异要记住:

  • glob 语法:legacy_vendor.* 只匹配一层。legacy_vendor.** 匹配这个包及其下面的所有内容,这才是 mypy 里 legacy_vendor.* 的含义。
  • 三个级别:一条规则只能是 "ignore"、"warn" 或 "error",没有 note 或 information 级别。
  • 没有类型的库:allowed-unresolved-imports 只消掉导入错误。如果库能解析到,但它的类型带来一堆噪音,可以用 replace-imports-with-any = ["somepkg.**"] 把整个模块当作 Any(来自文档,未实测)。
  • 规则名:官方的 mypy 与 Pyright 对照表 (opens in a new tab)列出了每个 mypy 错误码对应的 ty 规则。最常用的是这些:
mypy 错误码ty 规则
arg-typeinvalid-argument-type
assignmentinvalid-assignment
return-valueinvalid-explicit-return
attr-definedmissing-attribute
union-attrmissing-union-attribute(所有成员都没有该属性时是 missing-attribute)
call-argmissing-argument
operatorunsupported-operator
import-not-foundimport-not-found
overrideincompatible-method-override

加上配置后,import-not-found 错误消失,示例剩 7 条诊断。

第 4 步:修复不再生效的 type: ignore 注释

这是最不显眼的一处变化。ty 支持标准的 # type: ignore 注释,但对方括号里的错误码处理方式不同:

注释在 ty 1.0 里能屏蔽吗?
# type: ignore是,屏蔽整行所有诊断
# type: ignore[arg-type]否。不带 ty: 前缀的错误码会被忽略
# type: ignore[ty:invalid-argument-type]是,只屏蔽这条规则
# ty: ignore[invalid-argument-type]是,只屏蔽这条规则
# pyright: ignore[reportArgumentType]否

五行都实测过。后果是:如果团队按 mypy 的好习惯每次都写上错误码,这些屏蔽注释在 ty 下全部失效。rich 有 22 处 # type: ignore[...] 注释,22 处都带错误码。

要让两个检查器都接受,有两种写法。

方案 A,合并成一条注释。ty 文档给的是这种形式:

return int(raw) if raw else None  # type: ignore[return-value, ty:invalid-explicit-return]

ty 能接受。但如果 mypy 开了 warn_unused_ignores = true,mypy 2.4.1 会对它不认识的那部分报错(实测):

src/sales_report/load.py:23: error: Unused "type: ignore[ty:invalid-explicit-return]" comment  [unused-ignore]

方案 B,写两条注释。--add-ignore 生成的就是这种,两个检查器都不会报:

return "order-" + order_id  # type: ignore[operator]  # ty: ignore[unsupported-operator]

CI 里两个检查器并行期间用方案 B。mypy 下线后,把 # type: ignore[...] 那一半删掉。

第 5 步:用 --fix、--add-ignore 或 baseline 让检查通过

很少有人想在第一天就修完所有问题。ty 1.0 为此提供了三个工具,按下面的顺序配合使用比较顺。

5a. 应用安全的自动修复

uv run ty check --fix

在我们的示例里,它删掉了多余的 cast,输出 Found 7 diagnostics (1 fixed, 6 remaining).。它还会删除已经不起作用的、不带错误码的 # type: ignore 注释。提交前先看一遍 diff。

5b. 剩下的用行内注释屏蔽

uv run ty check --add-ignore
All checks passed!
Added 6 ignore comments

每条剩余诊断所在的行都会加上 # ty: ignore[rule] 注释。已经有 mypy 注释的行会保留原注释,再把 ty 注释追加在后面(实测)。这条路最快,但会改动很多文件,建议单独提交一个 commit。

5c. 或者用 baseline,把屏蔽信息放在代码之外

baseline 是一个 JSON 文件,记录现有的诊断。ty 会跳过里面记录的内容,只报新问题。它在 1.0 里还是预览功能,文件格式可能会变。

uv run ty check --update-baseline --baseline ty-baseline.json
Updated baseline `ty-baseline.json` with 6 diagnostics.

ty 打印的是文件的绝对路径,这里做了缩短。

然后在配置里指向这个文件,并把文件提交进仓库:

[tool.ty]
baseline = "ty-baseline.json"

文件按文件记录规则和列范围,不记行号。我们在一个已记录的错误上方插入三行,检查仍然通过(实测)。

怎么选:数量不多、又希望每处屏蔽都能在 review 里看到,用 --add-ignore。有几百条诊断、想先拦住新增问题,用 baseline。

第 6 步:把 ty 接入 CI

有三个细节要注意。

退出码:ty 遇到 warning 也返回 1,不只是 error(实测):

情况退出码
没有诊断0
只有 warning1
只有 warning,加 --exit-zero-on-warning0
有任意诊断,加 --exit-zero0
参数或配置无效2(文档)

如果想要和 mypy 类似的行为,只有 error 才让构建失败,加上 --exit-zero-on-warning。

注解:在 GitHub Actions 上,github 输出格式会把每条诊断变成 pull request 里的行内注解:

- name: Type check
  run: uv run ty check --output-format github

它输出的是 ::error title=ty (invalid-explicit-return),file=...,line=30,col=12 这样的行(实测)。另外还有 gitlab、junit 和 sarif 格式。

严格程度:ty 没有 --strict。mypy 要开 check_untyped_defs 才做的检查,ty 默认就包含了。文档建议用下面这组配置,最接近严格模式(本文未实测):

[tool.ty.rules]
dynamic-function-decorator-return = "error"
missing-type-argument = "error"
possibly-unresolved-reference = "warn"
unsound-return = "error"

ty 没有“这个函数没写类型标注”对应的规则(mypy 的 disallow_untyped_defs)。文档建议这部分交给 Ruff 的 ANN 规则。

从 ty beta 升级:renamed-rule

如果项目在 1.0 之前就用上了 ty,这次升级可能在代码没有任何改动的情况下让 CI 挂掉。有几条规则改了名,[tool.ty.rules] 里的旧名字现在会触发 warning。warning 的退出码是 1,所以 job 失败。

我们在 seaborn 仓库上复现了这个问题,它已经有 [tool.ty] 配置段(2026 年 10 月 7 日的 commit,用 ty 1.0.0 实测):

pyproject.toml:117:1: warning[renamed-rule] Rule `invalid-method-override` has been renamed to `incompatible-method-override`
pyproject.toml:119:1: warning[renamed-rule] Rule `unresolved-attribute` has been renamed to `missing-attribute`
pyproject.toml:125:1: warning[renamed-rule] Rule `call-non-callable` has been renamed to `not-callable`
pyproject.toml:126:1: warning[renamed-rule] Rule `call-top-callable` has been renamed to `call-to-function-with-unknown-signature`
pyproject.toml:127:1: warning[renamed-rule] Rule `invalid-return-type` has been renamed to `invalid-explicit-return`

解决办法是在配置里改名:

旧名字1.0 中的名字
invalid-method-overrideincompatible-method-override
unresolved-attributemissing-attribute
call-non-callablenot-callable
call-top-callablecall-to-function-with-unknown-signature
invalid-return-typeinvalid-explicit-return

这五条只是这个仓库恰好用到的。升级后跑一次 ty check,其余改名的规则也会连同新名字一起列出来。# ty: ignore[...] 注释里的旧名字会触发另一条警告 renamed-rule-in-ignore-comment,退出码同样是 1(实测),所以代码里的也要一起改。

pandas 和 NumPy 代码会有什么变化

数据科学代码依赖的库往往类型不完整,两个检查器在这里差别最大。我们拿一个典型的分析模块(读 CSV、分组、聚合、画图)分别跑了两边。

不装 pandas-stubs(实测):

  • mypy 在导入处就停了:Library stubs not installed for "pandas" [import-untyped]。
  • ty 输出 All checks passed!。它直接读 pandas 本身,推断不出来的部分当作 Unknown。这样很安静,但也意味着签名是 -> int 的函数返回 df["qty"].mean() 时不会被标出来。

装了 pandas-stubs(实测):

def top_region(df: pd.DataFrame) -> str:
    totals = df.groupby("region")["revenue"].sum()
    return totals.idxmax()          # both checkers: returns Hashable, not str
 
 
def bad(df: pd.DataFrame) -> int:
    return df["qty"].mean()         # mypy: float is not int. ty: no diagnostic
ty 1.0.0mypy 2.4.1
idxmax() 当作 str 返回报告报告
mean() 当作 int 返回未报告报告
reveal_type(df["qty"].mean())Unknownfloat

所以在大量使用 pandas 的代码上,ty 1.0 并不是一律“比 mypy 报得多”。在纯 Python 和 Pydantic 代码里它发现得更多,在一个 pandas-stubs 的场景里发现得更少。如果项目靠 mypy 加 pandas-stubs 来检查数值返回类型,先让两个检查器并行一段时间,对比之后再删 mypy。

不管哪种情况,都把 stubs 装上:

uv add --dev pandas-stubs

DataFrame 本身怎么写类型标注,见我们的 pandas 类型标注指南。

到底有多快?

速度是 ty 最主要的卖点,在一个小规模的本地测试里也得到了印证。两次运行都不带缓存,对象是 rich 的源码树(100 个文件,38,348 行,2026 年 11 月 7 日的 commit):

检查器耗时结果
mypy 2.4.1(仓库配置里的 --strict,--cache-dir=/dev/null)0.59 s1 个错误
ty 1.0.0(无配置)0.03 – 0.04 s42 条诊断

在一个小项目、一台机器上大约是 15 倍。这不算基准测试。Astral 自己的数据(厂商数据,本文未验证)称,ty 在其 CLI 基准测试的 18 个项目中有 16 个最快,OpenAI 迁移后速度提升的中位数是 24 倍。

比起耗时,那 42 条诊断更值得关注。其中 20 条所在的行已经有带错误码的 # type: ignore[...] 注释,而 ty 不认。5 条是可选依赖的 import-not-found:4 条来自 IPython 和 ipywidgets,仓库的 mypy 配置把它们忽略了;1 条来自 attr,这也是 mypy 报的唯一一个错误。剩下 17 条是 mypy 不报的问题。即使项目在 mypy --strict 下几乎没有报错,第一次跑 ty 也要留出时间。

现在该不该切换?

你的情况建议
新项目,还没用检查器直接用 ty。和 uv、Ruff 是同一套工具链,也没有历史注释要转换
mypy 只用了 Pydantic 插件适合迁移。Pydantic 支持是内置的,按第 1 到第 6 步做
mypy 用了其他插件(SQLAlchemy、自定义插件)先等等,或者让 ty 并行跑。ty 没有插件系统
Django、attrs、pytest1.0 发布说明里列出了内置支持,我们没有测
CI 里重度依赖 pandas-stubs两个检查器并行几周再对比(见 pandas 一节)
在 VS Code 里用 Pyright 或 Pylance命令行的迁移步骤相同,# pyright: ignore 注释需要转换。编辑器配置 (opens in a new tab)见文档,本文未实测
已经在用 ty beta升级,然后修掉 renamed-rule 警告

类型检查器能在代码运行之前发现一类 bug。而那些只有碰到真实数据才会出现的 bug,大多还是在 notebook 里调试。RunCell (opens in a new tab) 在 Jupyter 里放了一个 AI agent,可以运行单元格、读取实际的 DataFrame,补上静态检查器看不到的那部分。

常见问题

为什么加了 # type: ignore[arg-type] 的行,ty 还是报错?

ty 会忽略方括号里的错误码,除非以 ty: 开头。mypy 的错误码不会屏蔽任何诊断。在该行加上 # ty: ignore[invalid-argument-type],或者运行 ty check --add-ignore 一次性加好。

ty 会读取我的 mypy 或 Pyright 配置吗?

不会。它只读 pyproject.toml 里的 [tool.ty] 或 ty.toml 文件。把 ignore_missing_imports 换成 allowed-unresolved-imports,把 disable_error_code 换成 [tool.ty.rules] 下的规则级别。

大项目怎样迁移才不用修完所有错误?

先运行 ty check --fix,再从 ty check --add-ignore(行内注释)和 ty check --update-baseline --baseline ty-baseline.json(单独的文件)里选一个。两种做法都能让检查通过,之后只报新问题。

为什么只有 warning,ty 也让 CI 失败?

默认情况下,warning 和 error 的退出码都是 1。加上 --exit-zero-on-warning,或者把这条规则设为 "ignore"。

warning[renamed-rule] 是什么意思?

配置里用了 beta 时期的规则名。提示信息里有新名字,在 [tool.ty.rules] 里改过来就行。

ty 支持 mypy 插件吗?

不支持。它内置了对 Pydantic、Django、attrs 和 pytest 的支持,没有插件系统。

ty 和 mypy 可以并行跑吗?

可以,而且这样迁移更稳妥。每个需要屏蔽的行写两条注释 # type: ignore[code] # ty: ignore[rule],两个检查器就都不会报未使用的 ignore。

相关指南