Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import os
import time
from functools import wraps
def memoize_until_file_modified(filepath):
""""Memoize the data until the mtime of the file at filepath changes."""
def memoize_until_file_modified_decorator(func):
@wraps(func)
def decorated(*args, **kwargs):
try:
mtime = int(os.stat(filepath).st_mtime)
if decorated._last_mtime[filepath] != mtime:
decorated._last_mtime[filepath] = mtime
decorated._last_result = func(*args, **kwargs)
except AttributeError:
decorated._last_mtime = {}
decorated._last_mtime[filepath] = mtime
decorated._last_result = func(*args, **kwargs)
return decorated._last_result
return decorated
return memoize_until_file_modified_decorator
# Example Usage
@memoize_until_file_modified('test.txt')
def get_first_char_in_data():
print 'reading "%s" contents' % 'test'
data = file('test.txt').read()
return data[0]
@memoize_until_file_modified('test2.txt')
def get_second_last_char_in_data():
print 'reading "%s" contents' % 'test2'
data = file('test2.txt').read()
print 'read data :%s' % data
return data[-2]
file('test.txt', 'w').write('original content')
file('test2.txt', 'w').write('original content')
while True:
print '-'*60
print get_first_char_in_data()
print get_second_last_char_in_data()
print '-'*60
time.sleep(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment