My Python project has the following file structure.
module/
├── __init__.py
├── main.py
│
└── sub_module/
├── __init__.py
├── foo1.py
└── foo2.py
My goal is to import a class Bar
from foo1.py in main.py:
from sub_module.foo1 import Bar
It's important to know that foo1.py also imports from foo2.py, which currently works fine when I run python3 foo1.py
.
from foo2 import some_function
Both init.py files are empty.
Here is the exception that I currently get, when attempting to run python3 main.py
:
File "/.../module/main.py", line 3, in <module>
from sub_module.foo1 import Bar
File "/.../module/sub_module/foo1.py", line 24, in <module>
from foo2 import some_function
How can I get this working?
Thanks.
The problem is actually with from foo2 import some_function
in foo1.py
.
When running foo1.py
the file is found. This is because the current working directory is sub_module
and the path to the file is a relative.
When running main.py
this file 'foo2.py' is not found. This is because the current working directory is module
. For the relative path to find the file, you would need have from sub_module.foo2 import some_function
.
This isn't a great way of importing modules within a package.
The best way is to use absolute locations. This means that whichever file runs the code, it can find the module.
Firstly, removing __init__.py
in module
. I don't believe this is needed.
# main.py
from sub_module.foo1 import Bar
# foo1.py
from sub_module.foo2 import some_function
If the above is still not working, you need to check your current working directory. This can be done by adding the following to your main.py
. It's important that you include every directory from the working directory to the desired file.
import os
print(os.getcwd())
For more information on imports, the documentation is here: https://docs.python.org/3/reference/import.html