Python import structure

I want to have this structure for my project:

requirements.txt README.md .gitignore project/ __init__.py project.py core/ __init__.py base.py engines/ __init__.py engine1.py engine2.py utils/ __init__.py refine_data.py whatever.py 

The application starts from project/project.py . However, I constantly get import errors when using relative or absolute imports.

Both engines must be imported from project.core.base , utils must be imported from project.core.base , and project.py (main file) must be able to import from engines .

Absolute import does not work:

 # engines/engine1.py from project.core.base import MyBaseClass 

which gives an error:

 ImportError: No module named project.core.base 

But if I try relative imports instead

 # engines/engine1.py from ..core.base import MyBaseClass 

I get:

 ValueError: Attempted relative import beyond toplevel package 

I have seen other projects on Github structured in a similar way, but this seems to cause all kinds of problems. How can I make this work?

+5
source share
2 answers

Try using these imports:

engine1.py:

 from core import base 

refine_data.py:

 from core import base 

project.py

 from engines import engine1 

if you are using the pycharm mark project directory as root, then try running project.py. If you are not using pycharm, you can run project.py by going to the project directory and running the command:

 python project.py 
+2
source

Take a look at sys.path . It is likely that the top project directory is in the python path and sees your subpackages (i.e. utils , engines , etc.) as separate packages, so it gives you the error that when you try to import your package from the outside with relative import, and absolute import does not work, because it cannot find the directory of the top project, because it is not under any of the python paths.

The directory above the top directory of the project is what you need to add to the python path.

Ref.

 /path/is/here/project/core/... # Add this to the PYTHONPATH /path/is/here 
+4
source

Source: https://habr.com/ru/post/1238168/


All Articles