python3.8模块懒加载

1. 代码如下:

($是命令行提示符)

$ #目录结构
$ tree
.
├── a.py
└── impt.py

0 directories, 2 files
# impt.py
import sys
import importlib
from importlib.util import LazyLoader


for i, mp in enumerate(sys.meta_path):
    if str(mp) == "<class '_frozen_importlib_external.PathFinder'>":
        index = i
        path_finder = mp
        continue


class LazyPathFinder(object):
    
    def find_spec(self, fullname, path, target=None):
        spec = path_finder.find_spec(fullname, path, target=target)
        if spec is not None:
            spec.loader = LazyLoader(spec.loader)
        return spec


sys.meta_path[index] = LazyPathFinder()

import os
import a

print('a lazy imported')
print(a.b)
# a.py
print('exec a.py')

b = 2

2. 执行并查看输出结果

$ python impt.py 
a lazy imported
exec a.py
2

😀,大功告成!a模块懒加载了。

posted @ 2021-05-24 23:54  成民  阅读(381)  评论(0编辑  收藏  举报