Last active
December 20, 2015 15:59
-
-
Save mbarkhau/6158361 to your computer and use it in GitHub Desktop.
Class which will always give the fresh contents of a file
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
import codecs | |
from os.path import getmtime | |
from time import time | |
class FreshFile(object): | |
def __init__(self, filename, mode='r', encoding='utf-8', process_func=None, | |
max_age=0): | |
self._filename = filename | |
self._mode = mode | |
self._encoding = encoding | |
self._process_func = process_func | |
self._max_age = max_age | |
self._last_read = 0 | |
self._result_mtime = 0 | |
self._result = None | |
@property | |
def fresh_val(self): | |
with codecs.open(self._filename, self._mode, self._encoding) as f: | |
self._result = f.read() | |
if self._process_func: | |
self._result = self._process_func(self._result) | |
self._result_mtime = getmtime(self._filename) | |
return self._result | |
@property | |
def val(self): | |
if self._max_age: | |
now = time() | |
if self._result and now - self._last_read < self._max_age: | |
return self._result | |
self._last_read = now | |
if self._result and self._result_mtime == getmtime(self._filename): | |
return self._result | |
return self.fresh_val |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment