之前写过一篇关于循环引用import问题
http://my.oschina.net/1123581321/blog/176351
这里换一种方式,增加缓存,解决每次都要import效率低的问题
利用__getattr__实现python的lazy import
class LazyImport(object): """使用 os = LazyImport("os", globals(), locals()) # 此时还未导入os,这一行可以写在文件开始,import区域 os.getpid() # 调用__getattr__导入/从cache里获取 """ def __init__(self, name, globals={}, locals={}, fromlist=[], level=-1): 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)