Use dynamic import importlib.import_module() to solve relative import and absolute import problems

1. Background

According to the configuration of different projects, a code behavior needs to dynamically import the corresponding configuration files, library files and other dependencies before it can run.


2. Example 1

  • Project structure
 a文件夹
	│a.py
	│__init__.py
 b文件夹
	│b.py
	│__init__.py
	|__c文件夹
		  │c.py
		  │__init__.py
  • Code structure

c.py content

args = {
    
    'a':1}

class C:
    
    def c(self):
        pass
  • aims

a.py imports the classes and methods of c.py in the c folder under the b folder.

import importlib

params = importlib.import_module('b.c.c') #绝对导入
params_ = importlib.import_module('.c.c', package='b') #相对导入

# 从params中取出需要的对象
params.args  # 取出变量
params.C     # 取出class C
params.C.c   # 取出class C中的方法c

3. Example 2

  • Project structure
├── clazz
│   ├── __init__.py
│   ├── a.py
│   └── b.py
└── main.py
  • Code structure

a.py code

def show():
    print("show A")

b.py code

def show():
    print("show B")
  • aims

Import the a and b modules in the clazz package to main.py.

import importlib

# 绝对导入
a = importlib.import_module("clazz.a")
a.show(). # show A

# 相对导入
b = importlib.import_module(".b", "clazz")
b.show(). # show B

Note that there is a bit of relative import, similar to the path. Generally speaking, you can use absolute import or direct import only after importing, relative import b = importlib.import_module(".b", "clazz") can take effect.

Guess you like

Origin blog.csdn.net/yjk13703623757/article/details/105721982