Importing package with same base package name

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 answer

  • answered 2017-10-11 10:03 Nils Werner

    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__)