Use this class if you expect to make the same os.path.* calls many
times during a short time. The first time you call a method with certain
arguments, the call is made, but all subsequent calls are served from a
# Instantiate a new file system cache.
fsc = FSCache()
# This call will stat the file system.
# This call will leave the file system alone, the cached result will be returned.
You may call any method which is available in os.path.
self.cache = dict()
def load_yaml_from_file(self, path):
if not 'load_yaml_from_file' in self.cache:
self.cache['load_yaml_from_file'] = dict()
if path in self.cache['load_yaml_from_file']:
f = open(path, 'r')
data = yaml.load(f)
self.cache['load_yaml_from_file'][path] = data
def __getattr__(self, name):
# if the function was already called with the same args, return
# the result from the cache
if name in self.cache:
if args in self.cache[name]:
# otherwise, make the call and store the result in the cache
result = getattr(os.path, name)(*args)
if not name in self.cache:
self.cache[name] = dict()
self.cache[name][args] = result
raise AttributeError("Module os.path has no method '%s'" % name)