Can I define optional packages in setuptools?

前端 未结 2 1806
星月不相逢
星月不相逢 2021-02-14 03:33

Currently one of my packages requires a JSON parser/encoder, and is designed to use simplejson if available falling back to the json module (in the sta

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 04:27

    AFAIK there is no way to define an optional package and there would be no use to do so. What do you expect when you define an optional package? That it is installed when it is not yet available? (that would somehow make it mandatory)

    No, IMHO the correct way to address this is in your imports where you want to use the package. E.g:

    try:
        from somespecialpackage import someapi as myapi
    except ImportError:
        from basepackage import theapi as myapi
    

    This of course requires that the two APIs are compatible, but this is the case with simplejson and the standard library json package.

提交回复
热议问题