编程语言
首页 > 编程语言> > 两个版本的python延时加载 python LazyImport 模块懒加载

两个版本的python延时加载 python LazyImport 模块懒加载

作者:互联网

两个版本均使用cache缓存

逻辑为:首先在缓存里查找mod,如果找到,直接返回,如果没有找到,导入mod存入缓存,再将缓存里的mod返回。

一个版本使用__import___:

class LazyImport(object):
    """使用
    os = LazyImport("os", globals(), locals()) # 此时还未导入os,这一行可以写在文件开始,import区域
    os.getpid() # 调用__getattr__导入/从cache里获取
    """
    
    def __init__(self, name, globals=None, locals=None, fromlist=None, level=0):
        if fromlist is None:
            fromlist = []
        if locals is None:
            locals = {}
        if globals is None:
            globals = {}
        self.cache = {}
        self.mod_name = name
        self.globals = globals
        self.locals = locals
        self.fromlist = fromlist
        self.level = level
    
    def __getattr__(self, name):
        mod = self.cache.get(self.mod_name)
        if not mod:
            mod = __import__(self.mod_name, self.globals, self.locals, self.fromlist, self.level)
            self.cache[self.mod_name] = mod
        return getattr(mod, name)

另一个版本使用 importlib.import_module  :

class LazyImport(object):
    def __init__(self, name):
        self.cache = {}
        self.mod_name = name
        
    def __getattr__(self, name):
        mod = self.cache.get(self.mod_name)
        if not mod:
            mod = importlib.import_module(self.mod_name)
            self.cache[self.mod_name] = mod
        return getattr(mod, name)

使用方法:

from keyboard import Keyboard

def test():
    kb = Keyboard()
    kb.xxx

等同于:

import LazyImport

def test():
    kb = LazyImport('keyboard ').Keyboard()
    kb.xxx

 

标签:__,name,python,self,cache,LazyImport,加载,locals,mod
来源: https://blog.csdn.net/yy007668/article/details/114737333