I have a project in python that uses a file structure similar to this:
program/
main.py
SubFolder/
module1.py
module2.py
TestFolder/
test.py
In this structure main.py imports module2.py and module2.py imports module1.py. Also test.py imports module2.py.
I have two problems with the imports in this folder structure.
When running the main.py the import in module2.py is as follows:
from SubFolder.module1 import *
Here the the folder of main.py is set as the root folder and all the imports are done from there. While when I run module2.py directly the import should be as follows:
from module1 import *
Because now the root folder is the folder of module2.py. This is a problem, because now the import statements constantly need to be changed when running from different files. Is there any solution to this?
The second problem is when I want to run test.py, this file imports module2.py. The way to import this should be:
from ..SubFolder.module2 import *
But this gives the following error message:
from ..SubFolder.module2 import *
ImportError: attempted relative import with no known parent package
I have looked at a lot of solutions for this, but could not find one that worked. Is there any way to fix this.
Is there someone that could explain to me how I could resolve these issues?
I have already looked at this: Relative imports in Python 3, but this does not resolve my issue.
CodePudding user response:
I suggest you just create empty __init__.py files in subFolder and then import it as following: from subFolder.module1 import *.
CodePudding user response:
create a __init__ file
program/
main.py
SubFolder/
__init__.py
module1.py
module2.py
TestFolder/
test.py
in __init__.py, import all the files in same directory
from SubFolder.module1 import *
from SubFolder.module2 import *
in main.py, import Subfolder
from Subfolder import *
function_inside_module1()
Now you can access any object in module1 and module 2
__init__.py works just like def __init__ in a class function
It will execute itself once the parent directory (module) is imported
so in main.py, it will be executed as:
from SubFolder.module1 import *
from SubFolder.module2 import *
function_inside_module1()
Note: with import Subfolder you will need to call functions like this:
import Subfolder
Subfolder.function_inside_module1()
we now look at the module 2 import problem, this is already solved when __init__.py in created because now python sees it as a module and can be imported anywhere
in module2
from SubFolder.module1 import *
will now work at any working directory
same for test.py,
from SubFolder.module2 import *
will also work in test.py
Warning: Do not do this in module files and expect normal results
# in module1:
from SubFolder.module1 import *
# AND in module2:
from SubFolder.module2 import *
this will cause circular import and result in import error or names being undefined
