R / Richie全部文章 ↑

Python · 5 分钟阅读

Python:自动格式化代码(PEP 8)

目录


PEP 8 是 Python 官方代码风格指南。手动对照 PEP 8 既费时又容易漏。用一个
格式化工具 + 一个 Lint 工具
是现代 Python 项目的标配:

工具 作用 速度 备注
ruff 格式化 + Lint + import 排序(一体化) 极快 当前推荐,Rust 编写
black 格式化(不可配置风格) 快 业界事实标准
isort 只做 import 排序 快 常和 black 配合
autopep8 修复部分 PEP 8 错误 中 老牌
yapf 格式化 中 Google 推出
flake8 / pylint Lint 工具 中 检查代码风格/错误

新项目推荐组合:ruff(一站式)。老项目保留 black + isort + flake8 也完全没问题。


1. ruff:一站式现代化工具

ruff 由 Astral 编写,速度比 flake8 快 10~100 倍,能替代 flake8 + isort + black 的大部分工作。

安装

pip install -U ruff
# 或用 uv
uv tool install ruff

常用命令

# 1) 检查:只看不改
ruff check .

# 2) 自动修复可修复的问题(import 排序、未使用变量等)
ruff check . --fix

# 3) 格式化(类似 black)
ruff format .

配置文件 pyproject.toml

[tool.ruff]
line-length = 100
target-version = "py311"

[tool.ruff.lint]
# 选择启用的规则集
select = ["E", "F", "I", "B", "UP", "N", "W"]
# E/F: pycodestyle + pyflakes
# I:   isort
# B:   flake8-bugbear
# UP:  pyupgrade(自动建议新语法)
# N:   pep8-naming
# W:   pycodestyle warnings

[tool.ruff.lint.isort]
known-first-party = ["myproject"]

[tool.ruff.format]
quote-style = "double"
indent-style = "space"

集成到 pre-commit

.pre-commit-config.yaml:

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.6.9
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

2. black:格式化的事实标准

安装与使用

pip install -U black
black .                # 格式化当前项目
black --check .        # 只检查不修改
black --diff .         # 显示将要改的 diff

配置文件 pyproject.toml

[tool.black]
line-length = 100
target-version = ["py311"]

black 不允许配置 大量风格选项(缩进、引号风格等都是固定的),这是它的设计哲学:
“统一胜过个人偏好”。这能最大化减少团队 PR 中的风格争论。


3. isort:专门整理 import

pip install -U isort
isort .                 # 自动排序
isort --check-only .    # 只检查

pyproject.toml:

[tool.isort]
profile = "black"        # 与 black 的格式兼容
line_length = 100
known_first_party = ["myproject"]

4. autopep8:传统方案

pip install -U autopep8

# 查看 diff,不修改
autopep8 --diff code.py

# 覆盖原文件
autopep8 --in-place code.py

# 递归处理整个目录
autopep8 --in-place --recursive .

# 启用更激进的修复(多次使用表示更激进)
autopep8 --in-place --aggressive --aggressive code.py

setup.cfg / pyproject.toml 配置(autopep8 优先读 pyproject.toml):

[tool.autopep8]
max_line_length = 100
ignore = ["E226", "E302", "E41"]
in-place = true
recursive = true

5. 一键修复编码 / 换行符

跨平台开发经常遇到 Windows 换行符(CRLF)混入 Linux 项目的问题。可以用 dos2unix:

# macOS:  brew install dos2unix
# Ubuntu: sudo apt install dos2unix
dos2unix file.py           # 单文件
dos2unix src/**/*.py       # 整目录(zsh 可用)
find . -name "*.py" -exec dos2unix {} \;

或用 Vim 临时改:

:set fileformat=unix   " 或 ff=dos
:wq

git 也能在仓库层做自动转换(不推荐全局开启):

git config core.autocrlf input   # 推荐:提交时统一为 LF

6. 在编辑器里自动格式化

编辑器 配置
VS Code 安装 Ruff / Black 扩展;"editor.formatOnSave": true
PyCharm Settings → Tools → File Watchers 监听 black/ruff
Vim / Neovim 用 conform.nvim 一键接入 ruff/black
Cursor 与 VS Code 一致

VS Code settings.json 示例:

{
  "[python]": {
    "editor.defaultFormatter": "charliermarsh.ruff",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": { "source.fixAll.ruff": "explicit" }
  }
}

7. CI 流水线

# .github/workflows/lint.yml
name: lint
on: [push, pull_request]
jobs:
  ruff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/ruff-action@v1
        with:
          args: "check --output-format=github"
      - run: ruff format --check .

8. 选型建议

你的情况 推荐
新项目,希望一套搞定 ruff(check + format)
已有项目用 black + isort + flake8 不必迁移,但可以逐渐引入 ruff
需要 IDE 严格类型检查 ruff + mypy / pyright
CI 时间紧(monorepo) ruff(10x+ 速度优势)
团队对“不可配置”反感 autopep8 或 yapf

9. 常见问题

  • black 和 isort 冲突? 配 isort profile = "black" 即可。
  • CI 报“格式错误”但本地没问题? 多半是 line-length / target-version 不一致,
    统一在 pyproject.toml 里配置。
  • 格式化后 import 顺序乱了? 用 isort 或 ruff(启用 I 规则集)。
  • 想保留个人风格(如单引号)? 切到 ruff + 自定义 quote-style;black
    是不能配置的。
  • 格式化工具有“破坏性”吗? 改格式不会影响语义,但会污染 blame。可以:
    1. 一次性全仓格式化后合一个“style: format” commit;
    2. 用 .git-blame-ignore-revs 让 git blame 跳过那次提交。