Paradoxis Paradoxis - 3 months ago 17
Python Question

Unable to import child from parent package python

I'm currently writing a web application in python that needs unit tests, however whenever I try to import a child module that's in another parent directory I get the following error:

$ python my_package/tests/main.py
Traceback (most recent call last):
File "my_package/tests/test.py", line 1, in <module>
from my_package.core.main import hello
ImportError: No module named my_package.core.main


File: my_package/core/main.py



hello = "Hello"


File: my_package/test/test.py



from my_package.core.main import hello

print(hello, "world!")


My directory structure:



$ tree
.
└── my_package
├── __init__.py
├── core
│   ├── __init__.py
│   └── main.py
└── tests
├── __init__.py
└── test.py


Could someone please explain what I'm doing wrong? Thank you for your time.

Answer

It is considered an anti-pattern to modify sys.path. If you want your package to be available to all subpackages, it's better to use setup.py development mode. Create setup.py in the root of your project:

from setuptools import setup

setup(
    name="you_project",
    version="0.0.0",
    packages=['my_package', ],
    install_requires=['requirement1', 'requirement2'],
)

Then run:

$python setup.py develop

After this you will be able to import my_packege from anywhere.

Comments