Importing package with same base package name

风流意气都作罢 提交于 2019-12-11 17:18:50

问题


I have a large library I want to split up. There are packages: hdx.data hdx.facades hdx.utilities

I want to move hdx.utilities to a separate project hdx-python-utilities (on PyPi) and then add it as a requirement to the project with the packages hdx.data and hdx.facades (hdx-python-api). The problem is that I get ImportError: No module named 'hdx.utilities' when doing from hdx.utilities.session import get_session in the project hdx-python-api.

Is there any way to make this work in both Python 3+ and 2.7 (without renaming the top level package name hdx in either of them) allowing both hdx-python-api and hdx-python-utilities to work in any project that installs them?


回答1:


There are three ways of doing namespaced packages:

  • Native (Python 3.3)
  • pkgutil-style (Python 2 and 3, compatible to native)
  • pkg_resources-style (incompatible to the above, deprecated, not recommended)

The recommended way of doing namespaced packages for Python 2 and 3 are pkgutil-style namespace packages:

You would create the following for hpx-python-api

setup.py
hpx/
    __init__.py     # namespace init, see content below
    data/
        __init__.py
        ...
    facades/
        __init__.py
        ...

and the following for hpx-python-utilities

setup.py
hpx/
    __init__.py     # namespace init, see content below
    utilities/
        __init__.py
        ...

The two __init__.py files for the namespace package needs to contain only the following:

__path__ = __import__('pkgutil').extend_path(__path__, __name__)


来源:https://stackoverflow.com/questions/46685339/importing-package-with-same-base-package-name

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