pyproject.toml配置工具与实践详解
请详细说明pyproject.toml的结构,包括如何配置setuptools、Black、isort、pytest、mypy、coverage等工具。
回答
孤独的心
pyproject.toml是PEP 518/517/621定义的Python项目配置文件,顶层结构:
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "myapp"
version = "0.1.0"
description = "示例项目"
readme = "README.md"
requires-python = ">=3.9"
authors = [{name = "Author", email = "author@example.com"}]
dependencies = ["fastapi>=0.100", "sqlalchemy>=2.0"]
[project.optional-dependencies]
dev = ["pytest>=7.0", "black>=23.0", "mypy>=1.0"]
[tool.setuptools.packages.find]
where = ["src"]
[tool.black]
line-length = 88
[tool.isort]
profile = "black"
[tool.pytest.ini_options]
minversion = "7.0"
testpaths = ["tests/"]
addopts = "-v --tb=short"
[tool.mypy]
strict = true
python_version = "3.9"
[tool.coverage.run]
source = ["myapp"]
[tool.coverage.report]
fail_under = 80
各工具配置说明:
[build-system]:必须,指定构建工具[project]:PEP 621,声明式包元数据[tool.*]:各工具的配置命名空间,替代setup.cfg和独立配置文件
优势:统一配置入口,减少项目根目录的配置文件数量。支持所有现代Python工具。