Home > Software design >  python structure for a project
python structure for a project

Time:10-30

I am trying to structure my project, but Im facing some difficulties in importing modules.

This is my project structure, I would like to import module_1 functions into module_2 under src_1.

src
--src_1
  -- module_1
    --__init__.py
  -- module_2
    --__init__.py
--src_2
  -- module_1
    --__init__.py
--src_3
  -- module_1
    --__init__.py

CodePudding user response:

In the init file from module_2:

from src.src1 import module_1

or

import .module_1

CodePudding user response:

Well the importing will depend on the the directory from where you are running the code.

In order to import module_1 functions into module_2 under src_1, you need to add another __init__.py file in src1.

Better to add __init__.py in all directories if you want to use use methods/classes from different directories.

Something like this:

src
  --src_1
    -- module_1
      --__init__.py
    -- module_2
      --__init__.py
    -- __init__.py
  --src_2
    -- module_1
      --__init__.py
    -- __init__.py
  --src_3
    -- module_1
      --__init__.py
    -- __init__.py
  -- __init__.py

CodePudding user response:

Try appending the path to module_1 into your system path.

Add the below code in your python file in module_2.

import sys
sys.path.append("full path till module_1")
  • Related