Reputation: 358
I am trying to organize my project and following is the hierarchy of the project:
-Project
--core
|--__init__.py
|--module_1.py
|--module_2.py
--env1
|--env1.py
--env2
|--env2.py
The project has multiple environments and all of them share the modules in the core directory. I am trying to import function1
from module1
in env1.py
and env2.py
:
from core.module_1 import function1
I am getting the following error:
ModuleNotFoundError: No module named 'core'
I also tried setting the path of the core directory but no luck. The import
works if the module is in the same directory as the script calling it or if the script calling the module is in the main directory (in my case, Project
). How do I import the modules from the core
directory to the environment directories?
Upvotes: 2
Views: 123
Reputation: 1952
You've got the exact same problem that has been causing me trouble for a lot of last week. Here's my final version. If somehow this creates a time-machine, send that function back to me from last week, would ya?
def load_function(filepath,func_name) -> "function":
"""Load any function from a given path to a .py script."""
return getattr(__import__(filepath,fromlist=[func_name]),func_name)
Upvotes: 2