Ruff :是一个用Rust编写的极快的 Python linter 和代码格式化程序
安装
pip install ruff
语法检查
要对代码运行 linter,我们使用
ruff check .
如果你想在单个文件上运行它,请这样做
ruff check <filename.py>
总共有 415 个错误。其中 33 个可以修复!
为了修复它们,我们使用标志--fix
,就像这样
ruff check --fix .
如您所见,已修复 33 个,剩余 383 个。
格式化
为了格式化,我们使用ruff format
ruff format .
您可能不会以这种方式使用 Ruff,并且您有一个编辑器,那么让我们看看如何设置它!
在 VS Code 中使用它
获取VSCode 扩展。
现在,就像“修复所有可自动修复的问题”一样简单
但更好的是,您可以在保存时执行此操作。
保存时格式化
如果你希望 Ruff 自动修复 lint 违规、组织导入和保存格式,请转到你的settings.json
文件
添加这个。
"[python]": {"editor.formatOnSave": true,"editor.codeActionsOnSave": {"source.fixAll": "explicit","source.organizeImports": "explicit"},"editor.defaultFormatter": "charliermarsh.ruff"
}
取决于您是否希望 Ruff在键入时或保存时运行 linting 。默认情况下,它是在键入时运行,但我更喜欢在保存时运行。
"ruff.lint.run": "onSave",
Jupyter 笔记本
通过该扩展,您可以使用命令来格式化、检查和组织笔记本中的导入内容。
要在保存时启用它,请添加以下内容。
"notebook.formatOnSave.enabled": true,
"notebook.codeActionsOnSave": {"source.fixAll.ruff": true,"source.organizeImports.ruff": true
}
使用预提交
要使用预提交,可以按照以下方法添加Ruff 的预提交钩子。
- repo: https://github.com/astral-sh/ruff-pre-commit# Ruff version.rev: v0.2.2hooks:# Run the linter.- id: rufftypes_or: [ python, pyi, jupyter ]args: [ --fix ]# Run the formatter.- id: ruff-formattypes_or: [ python, pyi, jupyter ]
带有 CLI 的 Jupyter Notebook
如果你正在使用笔记本的 CLI,则必须转到或pyproject.toml
,ruff.toml
并添加此行
extend-include = ["*.ipynb"]
更多集成
它支持许多其他集成。包括 Vim!