My task is that of caching. If the folder exists then load the cache from disk, if it doesnt create new cache. This is trivial, what bothers me is if I want to create third mode of noop (don't do anything relating to cache).
Currently I have this:
class HeavyCalculationClass:
def __init__(self, cache_dir=None)
self.use_cache = cache_dir is not None
if self.use_cache:
if os.path.exists(cache_dir):
if len(os.listdir(cache_dir) != 0:
self.cache_type = "write"
else:
self.cache_type = "read"
else:
os.mkdir(cache_dir)
self.cache_type = "write"
def __getitem__(self, idx):
if self.use_cache and self.cache_type=="read":
data = numpy.load(os.path.join(cache_dir, str(idx)+".npy"))
else:
data = very_heavy_calculation()
if self.use_cache and self.cache_type == "write":
numpy.save(os.path.join(cache_dir, str(idx)+".npy"), data)
return data
Is there any way to write this in a more elegant form?
:-)\$\endgroup\$