I want to import a module using import_module from importlib. When I do that the files I reference from my module are not found. If I import my module normally from the python shell (not using main.py) it works as expected. Also, if I add the path of MyModule.py to sys.path it works but from what I understand I'm not supposed to do that (commented out in the code below).
How can I get my referenced file to be loaded also when the module is loaded by import_module?
I have the following file structure
main.py
subfolders
folder1
__init__.py
MyModule.py
hello.py
Contents of main.py
from importlib import import_module
modulename = 'subfolders.folder1.MyModule'
print("Import module ", modulename)
module = import_module(modulename)
m_instance = module.MyModule()
m_instance.module_hello()
Contents of MyModule.py
#This is the solution that works but feels wrong
#import os, sys
#sys.path.append(os.path.dirname(__file__))
from hello import hello_world
class MyModule(object):
def __init__(self):
print("Init MyModule")
def module_hello(self):
hello_world()
Contents of hello.py
def hello_world():
print("Hello World!")
When I run this I get:
c:\git\PythonImportTest>python main.py
Import module subfolders.folder1.MyModule
Traceback (most recent call last):
File "main.py", line 5, in <module>
module = import_module(modulename)
File "C:\Miniconda3\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "c:\git\PythonImportTest\subfolders\folder1\MyModule.py", line 5, in <module>
from hello import hello_world
ImportError: No module named 'hello'