background
- A function needs to dynamically import the corresponding configuration file to run according to the configuration of different projects.
solve
- file structure
a
│ a.py
│__init__.py
b
│ b.py
│__init__.py
│
├─c
│ c.py
│ __init__.py
- Content in c.py
args = {'a':1}
class C:
def c(self):
pass
Purpose To import objects in c.py
from module asolution
import importlib
# 从b module 导入c module中的c.py中的对象全部对象
params = importlib.import_module('b.c.c') #绝对导入
params1 = importlib.import_module('.c.c',package='b') #相对导入
# 对象中取出需要的对象
params.args #取出变量
params.C #取出class C
params.C.c #取出class C 中的c 函数
The above is how to use the dynamic function import_module