poetry 根据 extras 安装不同的包版本

poetry install different package version based on extras

使用 python-poetry,我想根据我在安装过程中传递的额外内容安装不同的包版本。例如。我愿意

# when extra == 'a', install numpy == 1.20.0
$ poetry install -E a
# when extra == 'b', install numpy == 1.19.0
$ poetry install -E b

我用下面的 toml 文件试过了

[tool.poetry]
name = "demo-poetry"
version = "0.1.0"
description = ""
authors = ["tenticon"]

[tool.poetry.dependencies]
python = "^3.8"
numpy = [
    { version = "1.20.0", markers = "extra == 'a'", optional = true},
    { version = "1.19.0", markers = "extra == 'b'", optional = true}
]

[tool.poetry.extras]
a = [ "numpy" ]
b = [ "numpy" ]

[tool.poetry.dev-dependencies]
pytest = "^5.2"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

但是当我这样做时 $ poetry install -E a 我得到

  SolverProblemError

  Because demo-poetry depends on both numpy (1.20.0) and numpy (1.19.0), version solving failed.

我的诗歌版本是1.1.6

Poetry extras are sets of packages (e.g. a = ["numpy", "scipy"]) that can be optionally installed together with the main dependencies (poetry install -E a). When installing or specifying poetry-built packages, the extras defined in the toml file can be activated as described in PEP-508 definition of extras. Thus, the dependencies required by the a extra could be installed using pip install demo-poetry[a] (just like any other ).

确实可以使用environment markers as install conditions for dependencies (see list of PEP-508 environment markers). However, at the time of writing the environment marker extra is not returned by the relevant function get_marker_env(),因此作为安装约束被忽略。 PEP-508 文档还指出 extra 变量很特殊,目前没有针对它的规范。

无论是使用 extras 还是组(来自 pre-release 1.2.0a2)都不足以达到预期的结果。在这方面,我认为@finswimmer 的评论是正确的:组不是相互排斥的,但诗歌会检查依赖项解析是否在每种情况下都有效。

我最接近可接受的解决方案是根据 python 版本或 on the platform 定义条件。请注意,这些条件应始终互斥,否则会出错。

例如,如果您有以下 pyproject.toml:

[tool.poetry]
name = "demo-poetry"
version = "0.1.0"
description = ""
authors = ["vreyespue"]

[tool.poetry.dependencies]
numpy = [
    { version = "1.19.0", python = "~3.7"},
    { version = "1.20.0", python = "~3.9"}
]

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

您可以在不同的环境中安装不同版本的 numpy

$ poetry env use 3.7
  Using virtualenv: /***/demo-poetry-***-py3.7

$ poetry install
  Installing numpy (1.19.0)

$ poetry env use 3.9
  Using virtualenv: /***/demo-poetry-***-py3.9

$ poetry install
  Installing numpy (1.20.0)