I have a way to build a data structure (e.g. from some file contents):
def loadfile(FILE): return
Therefore, I can do things like
puppies = loadfile("puppies.csv")
In the above example, I spent a ton of time actually reading kitties.csv and creating a data structure that I never used. I would like to avoid this waste without constantly checking if not kitties whenever I want to do something. I would like to be able to do
puppies = lazyload("puppies.csv") # instant kitties = lazyload("kitties.csv") # instant print len(puppies) # wait for loadfile print puppies[32]
So, if I never try to do something with kitties , loadfile("kitties.csv") will never be called.
Is there a standard way to do this?
After playing a little with him, I produced the following solution, which works correctly and is rather concise. Are there any alternatives? Are there any flaws in using this approach, which I must remember?
class lazyload: def __init__(self,FILE): self.FILE = FILE self.F = None def __getattr__(self,name): if not self.F: print "loading %s" % self.FILE self.F = loadfile(self.FILE) return object.__getattribute__(self.F, name)
What could be even better if something like this works:
class lazyload: def __init__(self,FILE): self.FILE = FILE def __getattr__(self,name): self = loadfile(self.FILE)
But this does not work, because self is local. In fact, this ends with calling loadfile every time you do something.