Search code examples
pythonpipsetup.pypython-packaging

Can setup.py / pip require a certain version of another package IF that package is already installed?


I have two python packages (locust-swarm and locust-plugins). Neither has a strict requirement to the other, but they can work together, and my users install them separately.

Sometimes there is a breaking change in one or the other, and I want to make sure nobody installs incompatible versions (by updating package A but not package B, for example). Is there a way to specify a minimum version of this "pseudo-dependency" and fail the install if it is not satisfied? A check that is only done if the other package is already installed.

I do not want to add one package as a dependency of the other and force users of package A to install package B, just to be able to handle this case.

Probably this question has been asked before, but I couldnt find an answer.


Solution

  • I think you can do this in your A/setup.py file (and the same in your B/setup.py file, just change package_B_name to package_A_name:

    import importlib.util
    spec = importlib.util.find_spec(f'{package_B_name}')
    if spec is not None:
        requirements_list.append(f'{package_B_name}>={package_B_version}')
    

    Note that this only works in Python3.3+ and only source distributions. It will not work when installing from a binary wheel (.whl)