diff -r 188a469792c2 -r fbbe956229cc degal/utils.py --- a/degal/utils.py Fri Jun 05 19:30:28 2009 +0300 +++ b/degal/utils.py Fri Jun 05 19:30:53 2009 +0300 @@ -1,73 +1,53 @@ -import os, os.path - -import settings - """ Miscellaneous utilities """ -def isImage (fname) : - """ - Is the given filename likely to be an image file? - """ - - fname = fname.lower() - base, ext = os.path.splitext(fname) - ext = ext.lstrip('.') - - return ext in settings.IMAGE_EXTS +import functools -def readFile (path) : - fo = open(path, 'r') - data = fo.read() - fo.close() - - return data - -def fuzzyDecode (bytes) : - try : - return bytes.decode('utf8') - except UnicodeDecodeError : - return bytes.decode('latin1', 'replace') - -def readTitleDescr (path) : +class LazyProperty (property) : """ - Read a title.txt or .txt file + Lazy-loaded properties """ - if os.path.exists(path) : - content = readFile(path) - - if '---' in content : - title, descr = content.split('---', 1) - else : - title, descr = content, '' - - title, descr = fuzzyDecode(title), fuzzyDecode(descr) - - return title.strip(), descr.strip() - - return u"", u"" + def __init__ (self, func) : + """ + Initialize with no value + """ -def url (*parts, **kwargs) : - abs = kwargs.pop('abs', False) - up = kwargs.pop('up', 0) - trailing = kwargs.pop('trailing', False) - - return '/'.join(([""]*int(abs)) + ([".."]*up) + list(parts) + ([""]*int(trailing))) - -url_join = url + super(LazyProperty, self).__init__(func) -def path_join (*parts) : - return os.path.join(*[part for part in parts if part is not None]) - -def strip_path (path) : - return path.lstrip('.').lstrip('/') + self.value = None -def mtime (path) : - try : - return os.stat(path).st_mtime - except OSError : - # no such file or directory - return None + def run (self) : + """ + Run the background func and return the to-be-cached value + """ + return super(LazyProperty, self).__call__() + + def __call__ (self) : + """ + Return the cached value if it exists, otherwise, call the func + """ + + if not self.value : + # generate it + self.value = self.run() + + return self.value + +class LazyIteratorProperty (LazyProperty) : + """ + A lazy-loaded property that automatically converts an iterator/genexp into a list. + """ + + def run (self) : + """ + Wrap LazyProperty.run to return a list + """ + + return list(super(LazyIteratorProperty, self).run()) + +lazy_load = LazyProperty +lazy_load_iter = LazyIteratorProperty +