python3.8模块懒加载

2021-05-28 05:00

阅读:434

标签:ted   spec   index   加载   load   目录   tree   none   ade   

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) == "":
        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模块懒加载了。

python3.8模块懒加载

标签:ted   spec   index   加载   load   目录   tree   none   ade   

原文地址:https://www.cnblogs.com/lyg-blog/p/14806886.html


评论


亲,登录后才可以留言!