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
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.