I have a directory like this:
parent.py ------+
child1.py---+
child2.py---+
... etc
I can import the parent module like this:
importlib.import_module("parent"))
So, what is the best way to get the child module now that I already have the parent module? I've tried parent.child1, importlib.import_module("child1", parent), parent.import_module('child1'), etc. to no avail.
Any advice?
Thanks
-
Possible duplicate how to import a module in python with importlib import-moduleDrees– Drees2019年08月01日 21:54:20 +00:00Commented Aug 1, 2019 at 21:54
2 Answers 2
You can try to organize files in this way:
parent (directory)-+
__init__.py ---+
child1.py ---+
child2.py ---+
In init.py you can import from child* files and that will be available to import from outside the module in parent.
Example __init__.py. It can also be empty, but it must exist.
from child1 import foo
from child2 import bar
Use from outside:
from parent import foo
or
from parent.child1 import foo
This doesn't answer directly your question. But, after you reorganize files in above way try to use importlib again.
Comments
You can use the optional parameter package for this:
importlib.import_module("child1", package="parent")
Documentation reference: https://docs.python.org/3.7/library/importlib.html#importlib.import_module
Comments
Explore related questions
See similar questions with these tags.