0

I'm having project structure like below

code
 |
 -- core --
 |        |
 |        test1.py
 |        test2.py
 |---database--        
 |            |
 |            sample.py
 --main.py

main.py is entry point for my application, from main.py I can import test1 from folder core by following code from core import test1 and it works fine But when I try to import test2 from test1(both are on same folder core) I'm using the following in test1

import test2 
but I'm getting no module named test2 error

why is that so?

How can I import sample.py in database from test1.py module in core ?
Saranraj K
  • 412
  • 1
  • 7
  • 19
  • Your import is absolute (actually relative to the entries in `sys.path` which automatically includes your `code` folder). Use a relative import: `import .test2`. – Michael Butscher Sep 17 '21 at 12:55

2 Answers2

0

What do you have inside these files? Functions? Classes? You can try:

in test1.py: from .test2 import *

and in sample.py: from ..core.test1 import *

Charalarg
  • 75
  • 1
  • 9
0

First of all: Import statement docs

There are 4 main ways you can import modules or module attributes using import statement:

  1. Absolute module import import module_name.submodule.submodule
  2. Absolute limited import from module_name.submodule import module_attribute, module
  3. Relative limited import from .submodule import module_attribute, module
  4. Relative wildcard import from .submodule import *

What you should know for now: absolute imports resolves path from project root. In your case import test2 is telling python to load code/test2.py instead of code/core/test2.py. To fix this issue, either supply proper absolute path:

import core.test2

or switch to relative path:

  • from . import test2 if you import from code/core/test1.py
  • from .core import test2 if you import from code/main.py
  • from ..core import test2 if you import from code/database/sample.py

Warning: be aware of cyclic imports:

from .b import *
from .a import *
Adam Bright
  • 126
  • 1
  • 11