Search code examples
pythonresourcespyglet

Clear pyglet resource cache


Is there a way to clear the resources cache in pyglet? The source image for a resource changes on disk and I need to reload it, but pyglet uses the cached resource instead. This is what I do:

pyglet.resource.path = [self.path]
pyglet.resource.reindex()
self.img = pyglet.resource.image(self.filename)

Then the image file changes on the disk and I want to reload it and I do the above again, but pyglet seems to use the cached image instead.


Solution

  • I ran into this same problem when using pyglet. This is the solution that I came up with:

    def clear_cache(filename):
            if filename in pyglet.resource._default_loader._cached_images:
                del pyglet.resource._default_loader._cached_images[filename]
    

    It works for me!

    Explanation:

    After poking around in the pyglet source, it seems that the resource module records the image names in a dictionary called _cached_images.

    It also seems that when you use the resource module like you are doing in your example, an object called _default_loader is created in the resource module. Therefore, the cache is found in _default_loader._cached_images.

    I'm sure there's a better way to accomplish what I did, such as sub-classing resource and adding my own clear_cache method there. But I'm new to programming, and I didn't quite understand everything in the resource module, so this was the best that I came up with.