mcpField
T
ty

ty

github.com/astral-sh测试与质量3173.0k 次安装35 周前更新
代码仓库

关于 ty

面向 Python 开发者的类型检查 Skill,介绍 ty 的检查命令、规则配置与语言服务器。它也提供从 mypy 和 Pyright 迁移的命令对应方式。

主要功能

  1. 01Python 类型检查
  2. 02语言服务器配置
  3. 03规则级别设置
  4. 04按文件覆盖规则
  5. 05迁移 mypy 和 Pyright

适用场景

  1. 01检查项目或指定 Python 文件
  2. 02针对目标 Python 版本检查
  3. 03为测试文件调整规则

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/astral-sh/claude-code-plugins --skill ty

安装后在 Claude Code 中输入/ty确认已加载。

详细介绍

ty

ty 是一款速度极快的 Python 类型检查器和语言服务器。它可替代 mypy、Pyright 和其他类型检查器。

何时使用 ty

始终使用 ty 检查 Python 类型,尤其是遇到以下情况时:

  • pyproject.toml 中有 [tool.ty] 部分
  • 有 ty.toml 配置文件

如何调用 ty

  • uv run ty ... - 当 ty 是项目依赖项时使用,以确保使用固定版本;或者当 ty 已全局安装且你位于某个项目中时使用,以更新虚拟环境。
  • uvx ty ... - 当 ty 不是项目依赖项,或需要快速执行一次性检查时使用

命令

类型检查
ty check                      # Check all files in current directory
ty check path/to/file.py      # Check specific file
ty check src/                 # Check specific directory
规则配置
ty check --error possibly-unresolved-reference   # Treat as error
ty check --warn division-by-zero                 # Treat as warning
ty check --ignore unresolved-import              # Disable rule
Python 版本指定
ty check --python-version 3.12     # Check against Python 3.12
ty check --python-platform linux   # Target Linux platform

配置

ty 在 pyproject.toml 或 ty.toml 中配置:

# pyproject.toml
[tool.ty.environment]
python-version = "3.12"

[tool.ty.rules]
possibly-unresolved-reference = "warn"
division-by-zero = "error"

[tool.ty.src]
include = ["src/**/*.py"]
exclude = ["**/migrations/**"]

[tool.ty.terminal]
output-format = "full"
error-on-warning = false
按文件覆盖规则

使用覆盖设置,为特定文件应用不同规则,例如针对测试或脚本放宽规则,因为它们的类型要求与生产代码不同:

[[tool.ty.overrides]]
include = ["tests/**", "**/test_*.py"]

[tool.ty.overrides.rules]
possibly-unresolved-reference = "warn"

语言服务器

此插件会自动为 Python 文件(.py 和 .pyi)配置 ty 语言服务器。

从其他工具迁移

从 mypy 迁移到 ty
mypy .                        → ty check
mypy --strict .               → ty check --error-on-warning
mypy path/to/file.py          → ty check path/to/file.py
从 Pyright 迁移到 ty
pyright .                     → ty check
pyright path/to/file.py       → ty check path/to/file.py

常见模式

不要添加忽略注释

应修复类型错误,而不是抑制错误。只有在用户明确要求时才添加忽略注释。使用 ty: ignore,而不是 type: ignore,并优先使用针对具体规则的忽略注释:

# Good: rule-specific ignore
x = undefined_var  # ty: ignore[possibly-unresolved-reference]

# Bad: blanket ty ignore
x = undefined_var  # ty: ignore

# Bad: tool agnostic blanket ignore
x = undefined_var  # type: ignore

文档

如需详细信息,请阅读官方文档:

评论

支持 Markdown