使用tox创建环境时setuptools_scm断言失败:assert version is not None
问题现象
执行tox -e my_env_name创建环境时触发打包失败,报错核心信息:
打包后端执行失败(code=1),触发AssertionError:
C:\github\my-package-name.tox.pkg\Lib\site-packages\setuptools_scm\version.py:84: UserWarning: tag 'c0.1.2' no version found
warnings.warn(f"tag {tag!r} no version found")
[...]
File "C:\github\my-package-name.tox.pkg\Lib\site-packages\setuptools_scm\version.py", line 203, in _parse_tag
assert version is not None
AssertionError
当前检出的提交已存在有效版本标签v0.1.2,但仍触发错误。
问题根源
setuptools_scm在扫描git版本标签时,优先识别到了格式无效的c0.1.2标签,该标签无法被解析为合法版本号,进而触发断言失败。
解决步骤
1. 清理无效git标签
检查本地和远程仓库的标签列表,删除c0.1.2这个无效标签:
# 删除本地标签 git tag -d c0.1.2 # 若标签已推送到远程,同步删除 git push origin :refs/tags/c0.1.2
2. 限定setuptools_scm的标签匹配规则
如果仓库存在其他非版本用途的标签,可在pyproject.toml中明确指定只匹配v前缀的合法版本标签:
[tool.setuptools_scm] tag_regex = r'^v(?P<version>[0-9]+\.[0-9]+\.[0-9]+)$'
3. 强制指定版本跳过标签检测
临时绕过setuptools_scm的自动标签检测,直接指定版本号运行tox:
SETUPTOOLS_SCM_PRETEND_VERSION=0.1.2 tox -e my_env_name
或者在tox.ini中配置永久生效:
[testenv] passenv = SETUPTOOLS_SCM_PRETEND_VERSION commands_pre = set SETUPTOOLS_SCM_PRETEND_VERSION=0.1.2
4. 确保tox环境获取完整git数据
若tox的隔离打包环境无法读取完整git信息,可在tox.ini中添加git到允许外部命令列表:
[testenv] allowlist_externals = git
内容的提问来源于stack exchange,提问作者koks der drache

