本文目录导读:

核心工具链(推荐组合)
# 安装工具 pip install black isort flake8 pre-commit # black: 自动格式化(最主流的代码格式化工具) # isort: 自动整理import顺序 # flake8: 代码规范检查 # pre-commit: Git提交前自动检查
配置文件示例
pyproject.toml(推荐方式)
[tool.black]
line-length = 88
target-version = ['py38', 'py39', 'py310', 'py311']
include = '\.pyi?$'
extend-exclude = '''
/(
\.eggs
| \.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
)/
'''
[tool.isort]
profile = "black"
line_length = 88
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
ensure_newline_before_comments = true
[tool.flake8]
max-line-length = 88
extend-ignore = "E203, W503"
exclude = ".git,__pycache__,venv,.venv,build,dist"
.pre-commit-config.yaml
repos:
- repo: https://github.com/psf/black
rev: 23.12.0
hooks:
- id: black
language_version: python3.11
- repo: https://github.com/PyCQA/isort
rev: 5.13.2
hooks:
- id: isort
args: ["--profile", "black"]
- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
hooks:
- id: flake8
args: ["--max-line-length=88", "--extend-ignore=E203,W503"]
代码格式化前后对比
❌ 不规范代码示例
import os,sys
from datetime import *
from typing import List,Optional
def calculate(a,b,c=0,
d=None):
result = a + b + c
if d is not None:
result += d
return result
class userManager:
def __init__(self,name,age):
self.name = name
self.age=age
def get_info(self):
return f"Name:{self.name},Age:{self.age}"
# 多个import混在一起
import json
from collections import defaultdict
✅ Black + isort 格式化后
import json
import os
import sys
from collections import defaultdict
from datetime import datetime
from typing import List, Optional
class UserManager:
"""用户管理器类"""
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
def get_info(self) -> str:
return f"Name: {self.name}, Age: {self.age}"
def calculate(a: int, b: int, c: int = 0, d: Optional[int] = None) -> int:
"""执行基础运算"""
result = a + b + c
if d is not None:
result += d
return result
主流规范对比(团队选择参考)
| 规范标准 | 行长度 | 引号 | 空格 | 适用场景 |
|---|---|---|---|---|
| PEP 8 | 79 | 无强制 | 严格 | 官方标准 |
| Black | 88 | 双引号 | 自动 | 大型项目(零争议) |
| 80 | 双引号 | 宽松 | 谷歌内部 | |
| YAPF | 88 | 配置 | 可配置 | 兼容性需求 |
推荐选择:Black(最省心,避免格式化争论)
IDE集成配置
VS Code settings.json
{
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"editor.defaultFormatter": "ms-python.black-formatter"
},
"isort.args": ["--profile", "black"],
"flake8.args": ["--max-line-length=88", "--extend-ignore=E203,W503"]
}
PyCharm
- 安装插件:File → Settings → Plugins → 搜索
BlackConnect - 设置快捷键:Tools → Black Connect → Reformat with Black
- 配置OnSave:勾选
On code reformatting选项
CI/CD自动化(GitHub Actions)
创建 .github/workflows/lint.yml:
name: Python Lint
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install black isort flake8
- name: Check formatting with Black
run: black --check .
- name: Check import order with isort
run: isort --check --profile black .
- name: Lint with flake8
run: flake8 . --max-line-length=88 --extend-ignore=E203,W503
一键格式化脚本
创建 format_code.sh:
#!/bin/bash echo "🔧 开始格式化Python代码..." # 1. 排序import isort . # 2. 代码格式化 black . # 3. 规范检查 flake8 . --max-line-length=88 --extend-ignore=E203,W503 echo "✅ 格式化完成!"
使用方法:
chmod +x format_code.sh ./format_code.sh
常见问题处理
| 问题 | 解决方案 |
|---|---|
| Black把单引号全改双引号 | 默认行为,建议统一使用双引号 |
| 某些行我不想被格式化 | 添加 # fmt: off 和 # fmt: on 注释包围 |
| isort和Black冲突 | 在isort配置中设置 profile = "black" |
| 不想格式化某个文件 | 在 pyproject.toml 的 extend-exclude 中添加 |
| 团队有人不用工具 | 配置pre-commit + CI强制检查 |
最佳实践总结
- 入职第一天:让成员安装black + isort + pre-commit
- 代码审查:把格式问题交给工具,review只关注逻辑
- 配置共享:
pyproject.toml和pre-commit-config.yaml纳入仓库 - 持续集成:CI失败禁止合并PR
- 定期更新:每季度更新工具版本
按照上述配置,您团队的所有Python代码将自动统一格式,无需再为缩进、空格、引号、import顺序等琐事争论。