How to import python module or package in a Tree Structure Repo

Viewed 21

I have a project with several python files. But when I try to structure the file into different packages, I got some problems.

So the structure I want to make structure be like

Repo
|
+--Package1
|  +-- __init__.py
|  +-- code1.py
|  +-- code2.py (using class in code1.py)
+--Package2
|  +-- __init__.py
|  +-- code3.py (using class in code 2 and code 4)
|  +-- cdoe4.py
+ __init__.py
+ main.py (using function in code 3)
+ utils.py

All codes from code1.py to code4.py used the functions in utils.py.

But when I do from Package.code3 import Someclass. Because in code3.py, it imports codes in code2.py and code4.py. So I always get module code2 not found error.

I tried putting the following code in Package1/__init__.py

from Package1 import code1
from Package1 import code2

And similarly, putting the following code in Package2/__init__.py

from Package2 import code3
from Package2 import code4

But I still get the error. What can I do to import such structured files?


It seems adding sys.path.append('./Package') solved the problem. But I wonder why I need to add this line since I already imported package1.

I really appreciate it if you can answer it.

1 Answers

I've faced the same error. Resetting the python-path solved it for me.

set PYTHONPATH=.
Related