Created
June 10, 2010 12:42
-
-
Save rctay/432929 to your computer and use it in GitHub Desktop.
memoize yaml.load
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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