pyrefly-type-coverage by pytorch/pytorch
npx skills add https://github.com/pytorch/pytorch --skill pyrefly-type-coverage本技能将指导您使用 Meta 的类型检查器 Pyrefly 来改进 Python 文件中的类型覆盖。遵循这个系统化的流程,为文件添加适当的类型注解。
pyrefly.toml 配置的项目中首先,定位并删除文件顶部的任何 pyre-ignore-all-errors 注释:
# 移除类似这样的行:
# pyre-ignore-all-errors
# pyre-ignore-all-errors[16,21,53,56]
# @lint-ignore-every PYRELINT
这些指令会抑制整个文件的类型检查,必须移除才能启用正确的类型覆盖。
为更严格的类型检查添加子配置条目。打开 pyrefly.toml 并按照以下模式添加条目:
[[sub-config]]
matches = "path/to/your/file.py"
[sub-config.errors]
implicit-import = false
implicit-any = true
对于目录级别的覆盖:
[[sub-config]]
matches = "path/to/directory/**"
[sub-config.errors]
implicit-import = false
implicit-any = true
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
您也可以根据需要启用更严格的选项:
[[sub-config]]
matches = "path/to/your/file.py"
[sub-config.errors]
implicit-import = false
implicit-any = true
# 取消注释以下选项以进行更严格的检查:
# unannotated-attribute = true
# unannotated-parameter = true
# unannotated-return = true
执行类型检查器以查看所有类型错误:
pyrefly check <FILENAME>
示例:
pyrefly check torch/_dynamo/utils.py
这将输出一个包含行号和描述的类型错误列表。常见的错误类型包括:
Any关键:您的目标是解决所有错误。如果无法解决某个错误,可以使用 # pyrefly: ignore[...] 来抑制,但您应该首先尝试解决该错误。
系统地处理每个错误:
函数签名:
# 之前
def process_data(items, callback):
...
# 之后
from collections.abc import Callable
def process_data(items: list[str], callback: Callable[[str], bool]) -> None:
...
类属性:
# 之前
class MyClass:
def __init__(self):
self.value = None
self.items = []
# 之后
class MyClass:
value: int | None
items: list[str]
def __init__(self) -> None:
self.value = None
self.items = []
复杂类型: 关键:使用 Python >3.10 的语法,并优先使用 collections.abc 而非 typing 以获得更好的代码标准。
关键:对于更高级/通用的类型,如 TypeAlias、TypeVar、Generic、Protocol 等,请使用 typing_extensions
# 可选值
def get_value(key: str) -> int | None: ...
# 联合类型
def process(value: str | int) -> str: ...
# 字典和列表
def transform(data: dict[str, list[int]]) -> list[str]: ...
# 可调用对象
from collections.abc import Callable
def apply(func: Callable[[int, int], int], a: int, b: int) -> int: ...
# 用于泛型的 TypeVar
from typing_extensions import TypeVar
T = TypeVar('T')
def first(items: list[T]) -> T: ...
对特定行使用 # pyre-ignore:
如果某一行难以正确键入类型(例如,动态元编程),您可以仅忽略该行:
# pyrefly: ignore[attr-defined]
result = getattr(obj, dynamic_name)()
关键:除非必要,否则避免使用 # pyre-ignore。在可能的情况下,我们可以实现存根,或重构代码以使其更具类型安全性。
添加注解后:
重新运行 pyrefly check 以验证错误是否已解决:
pyrefly check <FILENAME>
修复可能出现的任何新错误,这些错误可能来自您添加的注解
重复直到干净 - 继续操作,直到 pyrefly 报告没有错误
为了使类型覆盖的 PR 易于管理,您应该在完成一个文件后提交更改。
从函数签名开始 - 返回类型和参数类型通常是最高优先级
使用 from __future__ import annotations - 在文件顶部添加此导入以支持前向引用:
from __future__ import annotations
利用类型推断 - Pyrefly 可以推断许多类型;重点关注函数边界
检查现有的类型存根 - 对于外部库,检查是否存在类型存根
使用 typing_extensions 获取新功能 - 为了兼容性:
from typing_extensions import TypeAlias, Self, ParamSpec
使用 TypeAlias 记录复杂类型:
from typing import Dict, List, TypeAlias
ConfigType: TypeAlias = Dict[str, List[int]]
def process_config(config: ConfigType) -> None: ...
# 1. 打开文件并移除 pyre-ignore-all-errors
# 2. 在 pyrefly.toml 中添加条目
# 3. 检查初始错误
pyrefly check torch/my_module.py
# 4. 迭代添加注解
# 5. 更改后重新检查
pyrefly check torch/my_module.py
# 6. 重复直到干净
每周安装次数
163
代码仓库
GitHub 星标数
98.5K
首次出现
2026年2月5日
安全审计
安装于
opencode162
gemini-cli161
kimi-cli159
codex159
amp158
github-copilot158
This skill guides you through improving type coverage in Python files using Pyrefly, Meta's type checker. Follow this systematic process to add proper type annotations to files.
pyrefly.toml configurationFirst, locate and remove any pyre-ignore-all-errors comments at the top of the file:
# REMOVE lines like these:
# pyre-ignore-all-errors
# pyre-ignore-all-errors[16,21,53,56]
# @lint-ignore-every PYRELINT
These directives suppress type checking for the entire file and must be removed to enable proper type coverage.
Add a sub-config entry for stricter type checking. Open pyrefly.toml and add an entry following this pattern:
[[sub-config]]
matches = "path/to/your/file.py"
[sub-config.errors]
implicit-import = false
implicit-any = true
For directory-level coverage:
[[sub-config]]
matches = "path/to/directory/**"
[sub-config.errors]
implicit-import = false
implicit-any = true
You can also enable stricter options as needed:
[[sub-config]]
matches = "path/to/your/file.py"
[sub-config.errors]
implicit-import = false
implicit-any = true
# Uncomment these for stricter checking:
# unannotated-attribute = true
# unannotated-parameter = true
# unannotated-return = true
Execute the type checker to see all type errors:
pyrefly check <FILENAME>
Example:
pyrefly check torch/_dynamo/utils.py
This will output a list of type errors with line numbers and descriptions. Common error types include:
Any usageCRITICAL : Your goal is to resolve all errors. If you cannot resolve an error, you can use # pyrefly: ignore[...] to suppress but you should try to resolve the error first
Work through each error systematically:
Function signatures:
# Before
def process_data(items, callback):
...
# After
from collections.abc import Callable
def process_data(items: list[str], callback: Callable[[str], bool]) -> None:
...
Class attributes:
# Before
class MyClass:
def __init__(self):
self.value = None
self.items = []
# After
class MyClass:
value: int | None
items: list[str]
def __init__(self) -> None:
self.value = None
self.items = []
Complex types: CRITICAL : use syntax for Python >3.10 and prefer collections.abc as opposed to typing for better code standards.
Critical : For more advanced/generic types such as TypeAlias, TypeVar, Generic, Protocol, etc. use typing_extensions
# Optional values
def get_value(key: str) -> int | None: ...
# Union types
def process(value: str | int) -> str: ...
# Dict and List
def transform(data: dict[str, list[int]]) -> list[str]: ...
# Callable
from collections.abc import Callable
def apply(func: Callable[[int, int], int], a: int, b: int) -> int: ...
# TypeVar for generics
from typing_extensions import TypeVar
T = TypeVar('T')
def first(items: list[T]) -> T: ...
Using# pyre-ignore for specific lines:
If a specific line is difficult to type correctly (e.g., dynamic metaprogramming), you can ignore just that line:
# pyrefly: ignore[attr-defined]
result = getattr(obj, dynamic_name)()
CRITICAL : Avoid using # pyre-ignore unless it is necessary. When possible, we can implement stubs, or refactor code to make it more type-safe.
After adding annotations:
Re-run pyrefly check to verify errors are resolved:
pyrefly check <FILENAME>
Fix any new errors that may appear from the annotations you added
Repeat until clean - Continue until pyrefly reports no errors
To keep type coverage PRs manageable, you should commit your change once finished with a file.
Start with function signatures - Return types and parameter types are usually the highest priority
Usefrom __future__ import annotations - Add this at the top of the file for forward references:
from __future__ import annotations
Leverage type inference - Pyrefly can infer many types; focus on function boundaries
Check existing type stubs - For external libraries, check if type stubs exist
Usetyping_extensions for newer features - For compatibility:
from typing_extensions import TypeAlias, Self, ParamSpec
Document complex types with TypeAlias :
from typing import Dict, List, TypeAlias
ConfigType: TypeAlias = Dict[str, List[int]]
def process_config(config: ConfigType) -> None: ...
# 1. Open the file and remove pyre-ignore-all-errors
# 2. Add entry to pyrefly.toml
# 3. Check initial errors
pyrefly check torch/my_module.py
# 4. Add annotations iteratively
# 5. Re-check after changes
pyrefly check torch/my_module.py
# 6. Repeat until clean
Weekly Installs
163
Repository
GitHub Stars
98.5K
First Seen
Feb 5, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode162
gemini-cli161
kimi-cli159
codex159
amp158
github-copilot158
Perl 5.36+ 现代开发模式与最佳实践 | 构建健壮可维护应用程序指南
952 周安装