Python 代码质量:Black、isort、Flake8、Mypy、Pylint 完整配置
Introduction
代码质量工具让代码审查更高效。本文讲解格式化工具 Black、import 排序 isort、静态检查 Flake8/Mypy/Pylint 的配置和集成,以及 pre-commit 钩子在 Git 提交前自动运行检查。
---
工具安装
pip install black isort flake8 mypy pylint
Black(格式化,自动风格统一)
# 最简单用法(覆写文件)
black myproject/
# 检查但不修改(CI 用)
black --check myproject/
# 设定行宽和目标 Python 版本
black --line-length=100 --target-version=py39 myproject/
# pyproject.toml
[tool.black]
line-length = 100
target-version = ['py39']
include = '.pyi?$'
exclude = '''
/(
.git
| .venv
| __pycache__
)/
'''
isort(import 自动排序)
isort myproject/
isort --check-only myproject/
# pyproject.toml
[tool.isort]
profile = "black" # 与 Black 配合
line_length = 100
Flake8(代码风格检查)
flake8 myproject/ --max-line-length=100 --ignore=E203,W503
# .flake8
[flake8]
max-line-length = 100
exclude = .git,__pycache__,.venv
ignore = E203,W503,E501
per-file-ignores =
__init__.py:F401
Mypy(静态类型检查)
mypy myproject/ --strict
# pyproject.toml
[tool.mypy]
python_version = "3.9"
strict = true
warn_unused_configs = true
disallow_untyped_defs = true
pre-commit(Git 钩子)
pip install pre-commit
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
- id: mypy
安装:pre-commit install。之后每次 git commit 自动运行检查。
GitHub Actions CI 集成
# .github/workflows/ci.yml
name: CI
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'}
- run: pip install black isort flake8 mypy
- run: black --check .
- run: isort --check-only .
- run: flake8 .
- run: mypy .
常见问题
Q1: Black 和 isort 冲突怎么办?isort 的 profile = "black" 设置确保两者兼容,不会冲突。
Q2: Mypy 报错太多怎么开始?先用 mypy --ignore-missing-imports,逐步开启严格模式。
Q3: pre-commit 每次 commit 都运行慢?首次运行会慢(下载/安装环境),之后只运行增量检查,用 pre-commit run --all-files 手动全量运行。
延伸阅读
- pytest 单元测试
- coverage.py 测试覆盖率
- GitHub Actions 进阶 CI/CD
---
作者:小马 | 绍大技术网 shaoda.net