hatch build 和 hatch publish 是构建与发布 python 包的核心命令,但需严格满足 pep 517/518 规范:pyproject.toml 必须正确定义 hatchling 构建后端、采用 src/ 目录结构、正确配置项目名称,并通过 hatch publish --repository pypi 显式推送至正式 pypi。

hatch build 和 hatch publish 是构建和分发 Python 开源库最直接的两个命令,但前提是项目结构、配置和环境都符合 PEP 517/518 规范。盲目运行只会报错或上传失败。
pyproject.toml 必须声明 hatchling 构建后端
很多失败源于 pyproject.toml 缺少或写错构建系统配置。Hatch 本身不负责构建,它调用的是后端(如 hatchling)。必须确保文件里有且仅有:
[build-system] requires = ["hatchling"] build-backend = "hatchling.build"
常见错误包括:
- 误写成
build-backend = "hatch.build"(hatch没有 build 后端) - 漏掉
requires,导致构建时找不到hatchling - 同时存在
setuptools和hatchling配置,造成冲突
src/ 目录结构是默认前提,别硬套传统 flat 结构
Hatch(配合 hatchling)默认期望包代码放在 src/<package_name>/</package_name> 下。如果你把 __init__.py 直接放在项目根目录,hatch build 会成功,但生成的 .whl 里不含模块,安装后 import 报错。
正确做法:
- 创建
src/example_pkg/目录 - 把所有包内文件(
__init__.py、main.py等)放进去 -
pyproject.toml中无需额外声明 source-dir ——hatchling默认识别src/ - 若坚持用根目录结构,需在
[tool.hatch.build.targets.wheel]下显式配置source-dir = ".",但不推荐
hatch publish 默认推送到 TestPyPI,不是 PyPI
执行 hatch publish 时,它不会直接上传到生产 PyPI。默认行为是推送到 TestPyPI,这是安全机制,但容易被忽略。
验证方式:
- 首次运行会提示 “Uploading to https://www.php.cn/link/79304cca1ad8a247a9bafffd5f4db436/legacy/”
- 上传后去 https://www.php.cn/link/79304cca1ad8a247a9bafffd5f4db436/project/your-package-name/ 查看
- 要发布到正式 PyPI,必须显式加
--repository pypi参数:hatch publish --repository pypi - 提前在
~/.pypirc或使用hatch config set pypi.token <token></token>配置凭据,否则会卡在认证
dist/ 下产物不等于可用包,得验证安装路径
hatch build 成功后,dist/ 下会出现 .whl 和 .tar.gz,但这只是构建结果。真正决定能否被用户 pip install 的,是 wheel 内部的 RECORD 和模块路径。
快速验证方法:
- 解压
.whl文件(它是 zip 格式),检查顶层是否为example_pkg-目录,内部是否含example_pkg/子目录及__init__.py - 用
pip install --find-links dist/ --no-index example_pkg在干净虚拟环境中本地安装测试 - 如果
import example_pkg失败,大概率是src/结构没对齐,或[project]表中name和目录名不一致
pyproject.toml 里一个空格、src/ 少一层、或者以为 hatch publish 默认上生产站 —— 这些细节不验证,打包就只是生成了两个文件,而不是一个可交付的开源库。Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











