diff options
author | coutinho <coutinho@esrf.fr> | 2015-03-26 12:21:41 +0100 |
---|---|---|
committer | coutinho <coutinho@esrf.fr> | 2015-03-26 12:21:41 +0100 |
commit | 6f2a9f4d65212ef253a5ce6fc173d52b8a470c57 (patch) | |
tree | 674c3ba22a326794b20abf345ec5e01c102a1b11 /lib/taurus/core/util/decorator/memoize.py | |
parent | 3d39d0a483286c6cc6abc58d5514dc5390104736 (diff) |
First commit in tauruslib. Restructure according to SEP10
Diffstat (limited to 'lib/taurus/core/util/decorator/memoize.py')
-rw-r--r-- | lib/taurus/core/util/decorator/memoize.py | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/lib/taurus/core/util/decorator/memoize.py b/lib/taurus/core/util/decorator/memoize.py new file mode 100644 index 00000000..4dbb1d2e --- /dev/null +++ b/lib/taurus/core/util/decorator/memoize.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +############################################################################# +## +## This file is part of Taurus +## +## http://taurus-scada.org +## +## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain +## +## Taurus is free software: you can redistribute it and/or modify +## it under the terms of the GNU Lesser General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## (at your option) any later version. +## +## Taurus is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU Lesser General Public License for more details. +## +## You should have received a copy of the GNU Lesser General Public License +## along with Taurus. If not, see <http://www.gnu.org/licenses/>. +## +############################################################################# + +import functools + + +class memoized(object): + '''Decorator. Caches a function's return value each time it is called. + If called later with the same arguments, the cached value is returned + (not reevaluated). + ''' + + def __init__(self, func): + self.func = func + self.cache = {} + + def __call__(self, *args): + try: + return self.cache[args] + except KeyError: + value = self.func(*args) + self.cache[args] = value + return value + except TypeError: + # uncachable -- for instance, passing a list as an argument. + # Better to not cache than to blow up entirely. + return self.func(*args) + + def __repr__(self): + '''Return the function's docstring.''' + return self.func.__doc__ + + def __get__(self, obj, objtype): + '''Support instance methods.''' + return functools.partial(self.__call__, obj) |