python3.8模块懒加载

时间:2021-05-25 18:05:28   收藏:0   阅读:0

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模块懒加载了。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!