Search code examples
pythonclasspackage

import package name, but python identify package as module


structure of whole program


packageTest
    │  __init__.py
    │
    ├─packa
    │      __init__.py
    │
    └─packb
            hello.py
            __init__.py


more information

packageTest.__init__.py is a empty file

packa.__init__.py:

from ..packb import hello
hello.hello()

packb.__init__.py:

import hello

hello.hello()

packb.hello.py:

class hello:
    def __init__(self):
        print("Hello world!")

I'm tring import packb.hello.py by packa.__init__.py, but when I run it:

from ..packb import hello
ImportError: attempted relative import with no known parent package

I search some resources, which say create a __init__.py file in a folder will let python identify it as a package. Is there need more operate?

because of I use relative path, I don't want change sys.path if possible.


Solution

  • You have to install your project as a Python package. Without this, Python won't be able to import code between your submodules unless they are all in one folder. Changing sys.path is hacky und totally no necessary! To make it a package, create a setup.py in the root of your project (e.g. packageTest):

    ## In setup.py
    import setuptools
    
    setuptools.setup(
        name="my package",
        version="1.0",
        packages=["packa", "packb"]
    )
    

    Then you can simply run pip install -e . while in the project root. This installs your package in an editable mode (so you can change stuff without having to reinstall the code every time).

    Adjust the import statement to be absolute (which is recommended), and your code will run.

    from packb import hello
    
    hello.hello()