Search code examples
pythonpipsetuptools

Installing dependency on condition


I have a Python package P that has requirement A and requirement B3.4, but A has requirement B4.1. However, I know P can work just fine with B4.1 for some cases. I would like to be able to pip install package P and only install B3.4 if another version of B is not found in the target environment.

I have tried the following:

  • Inheritance from setuptools.command.install.install to override install command as explained here: https://blog.niteo.co/setuptools-run-custom-code-in-setup-py/. I tried checking and installing B after and before install.run
  • Trying to import B and add B3.4 as a requirement if the import does not succeeds. It turns out that B3.4 is always added, even if B4.1 is already installed.

Is there any reason for which it may not work? What other alternatives do I have?

Thank you!


Solution

  • I don't think you have any clean solution, you will have to use some trick.

    Solutions involving a dynamic check at build-time (i.e. code in setup.py) are quite limited, as they won't work once a wheel is built.

    Solutions involving a dynamic check at run-time are not best practice, and also have lots of issues (loading a module that was installed in-process is tricky).

    A possible work-around I can think of right now, would be to move P's requirement on B==3.4 to optional dependencies (extras), but it also has obvious limitations. As long as it's clearly explained in the documentation of P, and the side effects are clearly stated, I would say that is fair game.