I have a huge config file that I need to parse to get different configuration parameters at several classes/modules. I have created a separate module with function to do the parsing and other modules can call this to get the parsed file output.
I have come across this post Understanding __get__ and __set__ and Python descriptors which says property descriptors get can be used to cache expensive operations.
Here is what I am trying to do:
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]
then in another class I am doing this:
def load_config_file(self):
"""
"""
with open('/etc/test.json') as json_file:
return json.loads(json_file)
How can I decorate the load_config_file such that the actual load from json file is called only once no matter how many modules/classes call this?
If I do
@Lazy
def load_config_file(self, file):
how would I pass the instance parameter? Can someone explain me how to achieve this?