使用python __get__延迟加载昂贵的操作

时间:2014-11-12 20:58:59

标签: python lazy-loading lazy-evaluation

我有一个庞大的配置文件需要解析才能在多个类/模块中获取不同的配置参数。我创建了一个单独的模块,其中包含用于解析的函数,其他模块可以调用此函数来获取解析后的文件输出。

我遇到过这篇文章Understanding __get__ and __set__ and Python descriptors,其中称属性描述符 get 可用于缓存昂贵的操作。

以下是我要做的事情:

class Lazy(object):
"""Lazy attribute evaluation decorator class"""
    def __init__(self, f):
        self.f = f
        self.cache = {}
    def __get__(self, instance, owner):
        if instance not in self.cache:
            self.cache[instance] = self.f(instance)
        return self.cache[instance]

然后在另一个班级我这样做:

def load_config_file(self):
    """
    """
    with open('/etc/test.json') as json_file:
        return json.loads(json_file)

如何装饰load_config_file,以便无论有多少模块/类调用此命令,json文件的实际加载只被调用一次?

如果我这样做

@Lazy
def load_config_file(self, file):

我如何传递实例参数?有人能解释我如何实现这个目标吗?

0 个答案:

没有答案