Help Understanding weakref (lazyloader)

Ripter Ripter001 at
Thu Sep 4 04:46:14 CEST 2008

I found this script at
And I can't quite figure out how it works. I was wondering if someone
could clarify it for me.
The Code is:

import pygame
import weakref

class ResourceController(object):
    def __init__(self, loader):
            names = {},
            cache = weakref.WeakValueDictionary(),
            loader = loader

    def __setattr__(self, name, value):
        self.names[name] = value

    def __getattr__(self, name):
            img = self.cache[name]
        except KeyError:
            img = self.loader(self.names[name])
            self.cache[name] = img
        return img

class ImageController(ResourceController):
    def __init__(self):
        ResourceController.__init__(self, pygame.image.load)

My question is why does the __setattr__ set the value to
self.names[name] instead of self.cache[name]?

More information about the Python-list mailing list