Original Note

4.3 Packaging Code For Release And Distribution - Read

4.3 Packaging Code For Release And Distribution

正文

Install poetry

python3 -m pip install poetry

To test, we can ask where Poetry is installed:

which poetry

OUTPUT

/home/alex/python-intermediate-inflammation/venv/bin/poetry

配置虚拟环境

poetry config virtualenvs.in-project true

情况 1:已经手动创建虚拟环境

此时 Poetry 会使用当前已激活的 .venv。运行:

poetry install

依赖会安装到这个环境中。

情况 2:没有手动创建虚拟环境

直接运行:

poetry install

Poetry 会自动创建虚拟环境。

配置:

poetry config virtualenvs.in-project true

只是告诉 Poetry:

以后需要自动创建虚拟环境时,
请创建在当前项目的 .venv/ 中,
不要创建在 Poetry 的全局缓存目录中。

不会移动、重建或覆盖已有虚拟环境

Setting up our Poetry Config

Poetry uses a pyproject.toml file to describe the build system and requirements of the distributable package.

Make sure you are in the root directory of your software project and have activated your virtual environment, then we are ready to begin.

To create a pyproject.toml file for our code, we can use poetry init. This will guide us through the most important settings - for each prompt, we either enter our data or accept the default.

poetry init

两类依赖

运行时依赖

程序正常运行必须安装的库,例如:

import numpy
import matplotlib
poetry add matplotlib numpy

它们会被写入 pyproject.toml 的运行依赖列表:

[project]
dependencies = [
    "matplotlib",
    "numpy"
]

开发依赖

只在开发、测试和检查代码时使用,普通用户运行程序不需要,例如:

  • pytest:运行测试
  • pylint:代码检查
  • black:代码格式化

添加方式:

poetry add --group dev pylint

配置大致会变为:

[tool.poetry.group.dev.dependencies]
pylint = "^3.0"

--group dev 表示将它放入名为 dev 的开发依赖组,而不是运行依赖。

poetry add 会同时做三件事

执行:

poetry add numpy

Poetry 会:

  1. 修改 pyproject.toml,记录依赖要求;
  2. 修改或创建 poetry.lock,记录精确解析结果;
  3. 将依赖安装到当前虚拟环境。

Packaging Our Code

分发包名称

写在 pyproject.toml 中:

[project]
name = "inflammation"

它是用户安装时使用的名字:

pip install inflammation

分发包名称可以使用连字符:

name = "inflammation-analysis"

模块包名称

它是源代码目录名:

inflammation/
└── __init__.py

也是用户在 Python 中导入的名字:

import inflammation

模块名必须是合法的 Python 标识符,因此不能写:

import inflammation-analysis

Python 会把它理解成:

inflammation 减去 analysis

所以模块包通常使用下划线:

import inflammation_analysis

分发包名称:

  • 面向安装者;
  • 应在包仓库中避免重名;
  • 可以使用连字符;
  • 例如 pip install inflammation-analysis

模块包名称:

  • 面向 Python 代码;
  • 应简短、稳定;
  • 必须是合法 Python 标识符;
  • 例如 import inflammation_analysis
poetry build

This should produce two files for us in the dist directory. The one we care most about is the .whl or wheel file. This is the file that pip uses to distribute and install Python packages, so this is the file we would need to share with other people who want to install our software.

Now if we gave this wheel file to someone else, they could install it using pip - you do not need to run this command yourself, you have already installed it using poetry install above.

BASH

python3 -m pip install dist/inflammation*.whl