0

I have a folder structure below

my_project
  -- main.py
  -- dept_1
      -- process.py
      -- ops.py
  -- dept_2
      -- process.py
      -- ops.py
  -- common
      -- utils.py
      -- config.py
      -- meta_data.py

Now I have 2 decorators defined in utils.py. Now I want to use those inside ops.py which is again called from process.py.

I have used the following code.

in process.py

from dept_1 import ops.py
from common import utils
# to import some other functions

in ops.py

I have used all the below options

from common import utils
from common.utils import *
from common.utils import decorator_1, decorator_2

but every time, I face some import error, saying either

ImportError: No Module named 'utils'

or

utils has no attribute 'decorator_1

or

ImportError: can not import name 'decorator_1'

How to solve this issue?

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Rather than relying on manipulating `sys.path` manually. It may be helpful to read through https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time . This really helped me structure projects better so relative imports actually worked. – Axe319 Oct 07 '22 at 19:42
  • That being said, have you tried `import common.utils as utils` and `import dept_1.ops as ops`? – Axe319 Oct 07 '22 at 19:46
  • @Axe319, Yes I tried `import common.utils as utils` but this shows an attribute error: module 'common' has no attribute 'utils'. – Aditya Kumar Barik Oct 09 '22 at 14:37

1 Answers1

0

You can use the sys.path variable by adding the path to the utils.py module to it:

import sys

sys.path.append('<your-path>')

Note: you have to add the absolute path to the utils.py

Or you can add a relative path like this:

import sys
    
sys.path.append('../common/')

Note: you must add the path in the file in which you want to use the utils module

Now all you need to do is to import utils in your file and the interpreter will find it:

import sys
import utils       
sys.path.append('../common/')
Bemwa Malak
  • 1,182
  • 1
  • 5
  • 18