使用Python函数的返回值作为pyproject.toml中版本字段的值

问题描述 投票:0回答:1

我正在使用 setuptools 构建后端和

pyproject.toml
配置来创建 Python 包。我的包版本是动态的,现在我在
__version__
中设置
__init__.py
属性并在
pyproject.toml
中读取它。

pyproject.toml

[build-system]
requires = ["setuptools", "setuptools-scm"]
build-backend = "setuptools.build_meta"

[project]
name = "pkg1"
authors = [
    {name = "tad", email = "[email protected]"},
]
description = "my pkg desc"
requires-python = ">=3.9"
dynamic = ["dependencies", "version", "readme"]

[tool.setuptools.dynamic]
dependencies = {file = ["requirements.txt"]}
readme = {file = ["README.md"], content_type="text/markdown"}
version = {attr = "__version__"}
pkg1 的

__init__.py

def get_version():
    # some critiria to generate a valid version name
    return version

__version__ = get_version()

但是我想将

get_version()
__init__.py
移到其他地方,而且我应该能够调用该函数来填充
pyproject.toml
中的版本字段。有人可以帮助我理解如何修改
pyproject.toml
才能做到这一点吗?

setuptools python-packaging pyproject.toml
1个回答
2
投票

这就是我要做的(为了简洁和清晰,省略了一些不相关的细节,并省略了

...
):

pyproject.toml

[build-system]
# ...

[project]
name = "pkg1"
# ...
dynamic = ["version", "..."]

[tool.setuptools.dynamic]
# ...
# No version here!

setup.py

import setuptools

def get_version():
    version = "0.0.0"
    # Compute the version string here...
    return version

setuptools.setup(
    version=get_version(),
)

pkg1/__init__.py

import importlib.metadata

__version__ = importlib.metadata.version('pkg1')
# Where `pkg1` is the name of the distribution package, not the import package.

就我个人而言,如果可能的话,我会完全跳过

__version__
。在很多情况下,根本没有必要。如果有人想知道你的库的版本字符串
pkg1
,他们可以使用相同的代码
importlib.metadata.version('pkg1')
自己获取它。因为如果您的
__init__.py
中有它,那么它总是在导入时计算,即使它可能根本不会被使用。

© www.soinside.com 2019 - 2024. All rights reserved.