SuperAPI AI 工具集

python-packaging

编程与开发

查看项目

更新于 10-16 07:31

技能介绍

Python Packaging 是一项关于创建、组织和分发 Python 包的综合指南,重点介绍使用现代打包工具、pyproject.toml 配置以及发布到 PyPI 的流程。

用途

该技能适用于以下场景:

  • 创建用于分发的 Python 库
  • 构建带入口点的命令行工具
  • 将包发布到 PyPI 或私有仓库
  • 搭建 Python 项目结构
  • 创建带依赖项的可安装包
  • 构建 wheel 和源码分发包
  • 对 Python 包进行版本管理和发布
  • 创建命名空间包
  • 实现包元数据和分类器

核心概念

  1. 包结构
  • 源码布局:src/package_name/(推荐)
  • 扁平布局:package_name/(更简单但灵活性较差)
  • 包元数据:pyproject.toml、setup.py 或 setup.cfg
  • 分发格式:wheel(.whl)和源码分发包(.tar.gz)
  1. 现代打包标准
  • PEP 517/518:构建系统要求
  • PEP 621:pyproject.toml 中的元数据
  • PEP 660:可编辑安装
  • pyproject.toml:单一配置来源
  1. 构建后端
  • setuptools:传统、使用广泛
  • hatchling:现代、有明确约定
  • flit:轻量级,面向纯 Python
  • poetry:依赖管理 + 打包
  1. 分发
  • PyPI:Python 包索引(公开)
  • TestPyPI:生产前测试
  • 私有仓库:JFrog、AWS CodeArtifact 等

快速开始

最小包结构:

my-package/ ├── pyproject.toml ├── README.md ├── LICENSE ├── src/ │ └── my_package/ │ ├── init.py │ └── module.py └── tests/ └── test_module.py

最小 pyproject.toml:

[build-system] requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta"

[project] name = "my-package" version = "0.1.0" description = "A short description" authors = [{name = "Your Name", email = "you@example.com"}] readme = "README.md" requires-python = ">=3.8" dependencies = [ "requests>=2.28.0", ]

[project.optional-dependencies] dev = [ "pytest>=7.0", "black>=22.0", ]

包结构模式

模式 1:源码布局(推荐)

my-package/ ├── pyproject.toml ├── README.md ├── LICENSE ├── .gitignore ├── src/ │ └── my_package/ │ ├── init.py │ ├── core.py │ ├── utils.py │ └── py.typed # 用于类型提示 ├── tests/ │ ├── init.py │ ├── test_core.py │ └── test_utils.py └── docs/ └── index.md

优点:

  • 防止意外从源码目录导入
  • 测试导入更清晰
  • 隔离性更好

源码布局的 pyproject.toml:

[tool.setuptools.packages.find] where = ["src"]

模式 2:扁平布局

my-package/ ├── pyproject.toml ├── README.md ├── my_package/ │ ├── init.py │ └── module.py └── tests/ └── test_module.py

更简单,但:

  • 无需安装即可导入包
  • 对库来说不够专业

模式 3:多包项目

project/ ├── pyproject.toml ├── packages/ │ ├── package-a/ │ │ └── src/ │ │ └── package_a/ │ └── package-b/ │ └── src/ │ └── package_b/ └── tests/

更详细的模式文档位于 references/details.md。当上述导航层级信息不足时,可阅读该文件。