Another method of lazy, cached evaluation.

Kamilche klachemin at comcast.net
Wed Jan 18 20:52:09 EST 2006


If you wanted to avoid the __getattr__ __setattr__ speed hit, something
like this would work. However, you have to not mind calling a function
to get the data, instead of only getting the attribute:

class Cache(object):
    _cache = {}
    def __init__(self, filename):
        self.filename = filename
    def Get(self):
        obj = self._cache.get(self.filename, None)
        if not obj:
            obj = self._cache[self.filename] = Load(self.filename)
        return obj
    @staticmethod
    def Clear():
        print "\nClearing cache\n"
        Cache._cache = {}

class Sprite(Cache):
    def Draw(self):
        print self.Get()

class Sound(Cache):
    def Play(self):
        print self.Get()

def Load(filename):
    print "********** Open '%s' here" % filename
    suffix = filename.lower()[-3:]
    if suffix in ['png', 'bmp', 'jpg', 'tif']:
        tag = 'Image'
    elif suffix in ['wav', 'mp3']:
        tag = 'Sound'
    return "%s data from %s" % (tag, filename)


def main():
    sprite1 = Sprite('data/pic_1.png')
    sprite2 = Sprite('data/pic_2.png')
    sound1 = Sound('data/sound_22.wav')

    sprite1.Draw()
    sprite2.Draw()
    sound1.Play()
    sprite1.Draw()
    sprite2.Draw()
    sound1.Play()

    Cache.Clear()

    sprite1.Draw()
    sprite2.Draw()
    sound1.Play()
    sprite1.Draw()
    sprite2.Draw()
    sound1.Play()

main()




More information about the Python-list mailing list