You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

setup.py如何配置可选依赖版本限制且不强制安装依赖?

实现方案

你要的可选依赖版本约束完全可以实现,主流有两种落地路径,推荐优先选择运行时校验的方案,和pandas、plotly等开源包的设计逻辑完全对齐:

方案1:运行时校验(推荐)

不需要修改setup.py的依赖配置,只需要在调用依赖B的功能入口处增加版本校验逻辑即可,不会对不需要B的用户产生任何额外影响:

from packaging.version import parse as parse_version

def your_specific_func():
    try:
        import B
        # 按你的需求自定义版本范围,这里以>=1.0,<2.0为例
        if not (parse_version(B.__version__) >= parse_version("1.0") and parse_version(B.__version__) < parse_version("2.0")):
            raise ImportError(f"B版本不符合要求,当前为{B.__version__},需要范围>=1.0,<2.0,请执行:pip install 'B>=1.0,<2.0'")
    except ImportError as e:
        raise ImportError("调用该功能需要安装可选依赖B,版本范围>=1.0,<2.0,请执行:pip install 'B>=1.0,<2.0'") from e
    # 后续业务逻辑

同时你可以在setup.py的extras_require中增加B的版本声明,方便需要全功能的用户一键安装符合要求的依赖:

setup(
    name="A",
    install_requires=[
        # 你的其他强制依赖
    ],
    extras_require={
        "full": ["B>=1.0,<2.0"]
    }
)

用户如果需要用到B的功能,直接执行pip install A[full]就会自动安装符合版本要求的B,不需要手动处理版本问题。

方案2:安装阶段校验

如果你确实需要在用户安装A的时候,就对已经存在的B做版本校验,可以在setup.py中增加自定义校验逻辑:

from setuptools import setup
from pkg_resources import get_distribution, DistributionNotFound

try:
    b_ver = get_distribution("B").version
    if not (b_ver >= "1.0" and b_ver < "2.0"):
        raise RuntimeError(f"已安装的B版本{b_ver}不符合要求,需要>=1.0,<2.0,请先调整B的版本后再安装A")
except DistributionNotFound:
    # 用户未安装B,直接跳过校验
    pass

setup(
    name="A",
    # 其他配置,不要把B加到install_requires中
)

该方案的缺点是自定义安装逻辑在部分特殊场景(比如预构建wheel安装、离线安装)下可能不生效,所以除非有强需求,否则不推荐使用。

内容的提问来源于stack exchange,提问作者CIsForCookies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:24:00