Show
Ignore:
Timestamp:
01/03/2009 05:28:40 PM (19 months ago)
Author:
Friedrich Weber <fred@…>
Children:
6fd23d00b34f187e402f49614fcc3f5c69d3fae0
Parents:
7b6203a415e9073eb38fc7b42431d4525cccb28a
git-committer:
Friedrich Weber <fred@samurai-x.org> / 2009-01-03T17:28:40Z+0100
Message:

pyxcb: nicer cached_property implementation

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • pyxcb/pyxcb/util.py

    rdb8c5e re78624  
    3131log = logging.getLogger(__name__) 
    3232 
    33 CACHE_KEYWORD = '_cached' 
    3433# There is operator.methodcaller in Python 2.6! 
    3534methodcaller = lambda method: lambda value: getattr(value, method)() 
    3635 
    37 def cached(func): 
    38     # TODO: UGLY UGLY UGLY 
    39     def do_cache(self, *args, **kwargs): 
    40         if CACHE_KEYWORD not in func.func_dict: # table does not exist 
    41             func.func_dict[CACHE_KEYWORD] = {} 
    42         if self not in func.func_dict[CACHE_KEYWORD]: 
    43             func.func_dict[CACHE_KEYWORD][self] = func(self, *args, **kwargs) 
    44         return func.func_dict[CACHE_KEYWORD][self] 
    45     return do_cache 
     36def cached_property(func): 
     37    """ 
     38        `property`, but cached; 
    4639 
    47 def cached_property(func): 
    48     return property(cached(func)) 
     40        taken from http://code.activestate.com/recipes/576563/ - thanks. 
     41    """ 
     42    def getter(self): 
     43        try: 
     44            return self._property_cache[func] 
     45        except AttributeError: 
     46            self._property_cache = {} 
     47            self._property_cache[func] = ret = func(self) 
     48            return ret 
     49        except KeyError: 
     50            self._property_cache[func] = ret = func(self) 
     51            return ret 
     52    return property(getter) 
    4953 
    5054def reverse_dict(d):