Skip to content

Instantly share code, notes, and snippets.

@rctay
Created June 10, 2010 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rctay/432929 to your computer and use it in GitHub Desktop.
Save rctay/432929 to your computer and use it in GitHub Desktop.
memoize yaml.load
class memoize_file(object):
"""
The usual memoize pattern, but with special handling for functions that take
a file argument - use file.name as the key, instead of the file object
itself. This doesn't guarantee 'freshness' across file content changes, though.
"""
def __init__(self, func):
self.func = func
self._cache = {}
def __call__(self, stream):
key = stream
if isinstance(stream, file):
key = stream.name
if key in self._cache:
return self._cache[key]
self._cache[key] = result = self.func(stream)
return result
import yaml
yaml.load = memoize_file(yaml.load)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment