如何用Tox构建包含extra_requires依赖的Python Wheel文件?
问题描述
我有一个Python多模块项目,通过setup.py的extra_requires定义了额外依赖,现在想用Tox构建包含这些额外依赖的Wheel包,但不知道怎么实现。
项目结构如下:
my_project/ ├── setup.py ├── core/ │ ├── __init__.py │ └── core_code.py ├── api/ │ ├── __init__.py │ └── api_code.py ├── tests/ │ ├── __init__.py │ ├── test_core_code.py │ ├── test_api_code.py │ └── tox.ini
可通过pip install .安装核心依赖,或pip install .[api]安装核心+API额外依赖。
示例setup.py代码:
from setuptools import setup, find_packages setup( name='my_project', version='0.1.0', packages=find_packages(), install_requires=[ # core dependencies 'requests', ], extras_require={ 'api': [ # additional dependencies for the API 'flask', 'fastapi', ], }, )
目前已能通过Tox构建仅含核心模块的Wheel,对应的tox.ini配置:
[tox] envlist = py39 [testenv] description = 'Builds a core wheel file (from setup.py) and runs unit tests.' package = wheel deps = pytest commands = pytest tests
现在需要构建包含核心+[api]额外依赖的Wheel,尝试过以下伪代码配置但无效:
[testenv:api-full] description = 'Builds a wheel file with extra_requires and runs tests.' package = wheel [api] #<--- pseudocode deps = pytest commands =
解决方案
Tox没有直接通过package参数指定extras的内置方式,但可以通过两种方法实现需求:
方法1:自定义构建命令
直接在commands中调用pip wheel命令,显式指定要包含的extras:
[testenv:api-full] description = 'Builds a wheel file with [api] extras and runs tests.' deps = pytest commands = # 构建包含api额外依赖的wheel,输出到dist目录 pip wheel .[api] -w dist/ # 运行API相关测试(可选) pytest tests/test_api_code.py
这种方式直接通过pip生成包含api额外依赖声明的Wheel,生成的包元数据会包含核心+api的所有依赖要求。
方法2:使用Tox的extras配置项(Tox 3.20+)
如果使用Tox 3.20及以上版本,可利用extras配置项指定要包含的额外依赖,结合package = wheel使用:
[testenv:api-full] description = 'Builds a wheel file with [api] extras and runs tests.' package = wheel extras = api deps = pytest commands = pytest tests/test_api_code.py
该配置会让Tox在构建Wheel时自动包含setup.py中定义的api额外依赖,生成的Wheel包元数据会带有对应的依赖声明。
注意事项
- Wheel文件本身不会打包额外依赖的代码,只是在元数据中声明这些依赖。用户安装时需要执行
pip install my_project-0.1.0-py3-none-any.whl[api]才能安装包含额外依赖的版本;如果需要"全量"依赖的Wheel,需修改setup.py将api依赖合并到install_requires,但这不符合extras的设计初衷。 - 上述两种方法都能同时满足构建目标Wheel和运行对应测试环境的需求。
内容的提问来源于stack exchange,提问作者Adam Hughes
相关产品推荐
相关产品推荐

