How should I handle importing third-party libraries within my setup.py script?

有些话、适合烂在心里 提交于 2019-12-05 11:42:14

I'm ignoring licensing issues in this answer. You definetly need to take these into account before you really do a release.

Is it acceptable to rely on third-party libraries like this in setup.py

Yes, it is acceptable but generally these should be minimized, especially if these are modules which have no obvious use for the end-user. Noone likes to have packages they don't need or use.

what is the recommended approach to using them?

There are basically 3 options:

  • Bootstrap them (for example use pip to programmatically install packages). For example setuptools provides an ez_setup.py file that can be used to bootstrap setuptools. Maybe that can be customized to download and install appdirs.

  • Include them (especially if it's a small package) in your project. For example appdirs is basically just a single file module. Pretty easy to copy and maintain in your project. Be very careful with licensing issues when you do that!

  • Fail gracefully when it's not possible to import them and let the user install them. For example:

    try:
        import appdirs
    except ImportError:
        raise ImportError('this package requires "appdirs" to be installed. '
                          'Install it first: "pip install appdirs".')
    

You can mention install_requires with the dependencies list. Please check the python packaging guide here. Also you can provide a requirements.txt file so that it can be run at once using "pip install -r"

You could use pip to install the package programmatically if the import fails:

try:
    import appdirs
except ImportError:
    import pip
    pip.main(['install', 'appdirs'])
    import appdirs

In some circumstances you may need to use importlib or __import__ to import the package after pip.main or referesh the PATH variable. It could also be worthwhile to include a verification if the user really wants to install that package before installing it.

I used a lot of the examples from "Installing python module within code" and I haven't personally tried used this in setup.py files but it looks like it could be a solution for your question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!