0

hello i am working on my first python project and i have problem with importing from subfolders in project

for example this my project tree

C:\USERS\AHMAD\DESKTOP\myProject
│
├───project
│   │   __init__.py
│   │
│   ├───core
│   │       config.py
│   │       __init__.py
│   │
│   ├───libs
│   │       lib1.py
│   │       __init__.py
│   │
│   └───modules
│       │   __init__.py
│       │
│       ├───module1
│       |       script1.py
│       │       __init__.py
│       │
│       ├───module2
│       │       __init__.py
│       │
│       ├───module3
│       │       __init__.py
│       │
│       └───module4
│               __init__.py

now at script1 in module1 how can i import config file from core folder?? is that possible ? help please!!.

ahmad
  • 13
  • 1
  • 1
    https://stackoverflow.com/q/14132789/1032785 – jordanm Apr 13 '20 at 21:46
  • If "script1.py" is the main script where execution begins, you have to add the "project" folder to the Python path (sys.path) to do `from core import config`. – Michael Butscher Apr 13 '20 at 21:48
  • @MichaelButscher i saw some projects on github but i didn't know how it work when import they use the **mainProject folder** as a **package** and import from it for example at script1 they can use `from project.core import config` how can i do that with my project ?? – ahmad Apr 13 '20 at 22:16
  • thank you guys so much, finally i understand how it work now :) <3 – ahmad Apr 13 '20 at 23:09

2 Answers2

0

Try a relative import to navigate backwards:

from ...core import config

Each dot before 'core' represents a parent module starting from script1.py

So, the first one is 'module1', the second one is 'modules' and the third one is the 'project'.

0

This question has already been answered by: Relative imports for the billionth time

But to reiterate the point, assuming that script1.py is suppose to be a submodule of the package project, you can simply use either an absolute or relative import:

from project.core import config

or

from ...core import config

However, this DOES NOT mean you can run the script with python script1.py. This will not work (and will result in a ModuleNotFoundError). Relative and absolute imports ONLY work when the python file is being treated as a module. When you run a python file directly via python filename, it's being treated as the top level (main) python script and its __name__ attribute is set to "__main__". You typically shouldn't be executing module files anyways, however if you must, at dir level one above the package, run:

python -m project.modules.module1.script1
Jay Mody
  • 3,727
  • 1
  • 11
  • 27