Python - poetry(5)依赖规范

啥是依赖规范

可以以各种形式指定项目的依赖项,取决于依赖项的类型以及安装项目可能需要的可选约束

 

版本约束

^ 约束

编写规范允许的版本范围
^1.2.3 >=1.2.3 <2.0.0
^1.2 >=1.2.0 <2.0.0
^1 >=1.0.0 <2.0.0
^0.2.3 >=0.2.3 <0.3.0
^0.0.3 >=0.0.3 <0.0.4
^0.0 >=0.0.0 <0.1.0
^0 >=0.0.0 <1.0.0
  • 当最左边的数字为非 0,则以左一数字为主版本号,比如:^2.13.0,可以取 2.14.0,但不能取 3.0.0,因为主版本号已经变了
  • 如果左一的数字为 0,则以左二的数字为主版本号,比如:^0.1.0  可以取 0.1.1、0.1.19,但不能取 0.2.0,因为主版本号已经变了

 

~ 约束

编写规范允许的版本范围
~1.2.3 >=1.2.3 <1.3.0
~1.2 >=1.2.0 <1.3.0
~1 >=1.0.0 <2.0.0

和上面的 ^ 差不多,不过这个是次要版本,以第二个数字为基准

 

* 约束

有点像万能匹配符,写在哪里都可以

编写规范允许的版本范围
* >=0.0.0
1.* >=1.0.0 <2.0.0
1.2.* >=1.2.0 <1.3.0

 

比较符

就常规的>、< 符号了

>= 1.2.0
> 1
< 2
!= 1.2.3

 

确定的版本号或范围

>= 1.2,< 1.5

 

git 依赖

可以指定依赖项的 git 仓库地址

[tool.poetry.dependencies]
requests = { git = "https://github.com/requests/requests.git" }

默认会拉 git 仓库的 master 分支

 

也可以指定 branch、commit hash、tag

[tool.poetry.dependencies]
# Get the latest revision on the branch named "next"
requests = { git = "https://github.com/kennethreitz/requests.git", branch = "next" }
# Get a revision by its commit hash
flask = { git = "https://github.com/pallets/flask.git", rev = "38eb5d3b" }
# Get a revision by its tag
numpy = { git = "https://github.com/numpy/numpy.git", tag = "v0.13.2" }

 

路径依赖

如果依赖项位于本地目录,可以用 path

[tool.poetry.dependencies]
# directory
my-package = { path = "../my-package/", develop = false }

# file
my-package = { path = "../my-package/dist/my-package-0.1.0.tar.gz" }

 

url 依赖

如果依赖远程仓库的文件,可以用 url

[tool.poetry.dependencies]
# directory
my-package = { url = "https://example.com/my-package-0.1.0.tar.gz" }

 

可以通过 poetry add 来添加 url

poetry add https://example.com/my-package-0.1.0.tar.gz

 

Python 限制依赖项

指定仅应该以特定 Python 版本安装依赖项

[tool.poetry.dependencies]
pathlib2 = { version = "^2.2", python = "~2.7" }

 

[tool.poetry.dependencies]
pathlib2 = { version = "^2.2", python = "~2.7 || ^3.2" }

 

多个限制

假设依赖包

  • 版本小于等于 1.9 的时候,只能和 Python 2.7 到 Python 2.9 版本兼容
  • 版本大于 2.0 的时候,只能和 Python 3.4 + 版本兼容
[tool.poetry.dependencies]
foo = [
    {version = "<=1.9", python = "^2.7"},
    {version = "^2.0", python = "^3.4"}
]

 

使用环境限制

感觉比较少用,暂时不展开详解

[tool.poetry.dependencies]
pathlib2 = { version = "^2.2", markers = "python_version ~= '2.7' or sys_platform == 'win32'" }

 

markers 官方文档:https://www.python.org/dev/peps/pep-0508/#environment-markers

 

扩展依赖规范语法

当某个依赖项需要添加很多属性的时候,可读性就很差,如下

[tool.poetry.dev-dependencies]
black = {version = "19.10b0", allow-prereleases = true, python = "^3.6", markers = "platform_python_implementation == 'CPython'"}

 

使用新的语法格式

[tool.poetry.dev-dependencies.black]
version = "19.10b0"
allow-prereleases = true
python = "^3.6"
markers = "platform_python_implementation == 'CPython'"

依赖项的约束完全一样,只不过变成一行一个约束属性,可读性更强

 

posted @ 2021-09-15 10:58  小菠萝测试笔记  阅读(970)  评论(0编辑  收藏  举报