Ruff:把静态问题消灭在写代码时(续)
# F401:未使用的导入 → 自动删除
import os # 没有用到
# B006:可变默认参数 → 提醒修复
def get_items(ids: list = []): # 危险
# UP006:旧类型注解写法 → 自动升级
from typing import List, Dict
def func(items: List[Dict]): # 应该用 list[dict]
# SIM108:可以简化的三元表达式
x = True if condition else False # 可以简化成 x = condition
接到本地和 CI
本地保存时自动修复:
// .vscode/settings.json
{
"[python]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "charliermarsh.ruff"
}
}
pre-commit 配置:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.0
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
CI 里只检查不修复:
# .github/workflows/ci.yml
- name: Lint
run: ruff check . && ruff format --check .