Clean : (Grégory Starck) clean of some getattr code, bis.
[shinken.git] / shinken / memoized.py
blob51a5a2da0d2f4ab4e7d48165b5d7846da9122082
1 #!/usr/bin/env python
2 #Copyright (C) 2009-2010 :
3 # Gabes Jean, naparuba@gmail.com
4 # Gerhard Lausser, Gerhard.Lausser@consol.de
6 #This file is part of Shinken.
8 #Shinken is free software: you can redistribute it and/or modify
9 #it under the terms of the GNU Affero General Public License as published by
10 #the Free Software Foundation, either version 3 of the License, or
11 #(at your option) any later version.
13 #Shinken is distributed in the hope that it will be useful,
14 #but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 #GNU Affero General Public License for more details.
18 #You should have received a copy of the GNU Affero General Public License
19 #along with Shinken. If not, see <http://www.gnu.org/licenses/>.
22 class memoized(object):
23 """Decorator that caches a function's return value each time it is called.
24 If called later with the same arguments, the cached value is returned, and
25 not re-evaluated.
26 """
27 def __init__(self, func):
28 self.func = func
29 self.cache = {}
30 def __call__(self, *args):
31 try:
32 return self.cache[args]
33 except KeyError:
34 self.cache[args] = value = self.func(*args)
35 return value
36 except TypeError:
37 # uncachable -- for instance, passing a list as an argument.
38 # Better to not cache than to blow up entirely.
39 return self.func(*args)
40 def __repr__(self):
41 """Return the function's docstring."""
42 return self.func.__doc__
44 #import cPickle
48 #def memoized(function, limit=None):
49 # if isinstance(function, int):
50 # def memoize_wrapper(f):
51 # return memoized(f, function)
53 # return memoize_wrapper
55 # dict = {}
56 # list = []
57 # def memoize_wrapper(*args, **kwargs):
58 # key = cPickle.dumps((args, kwargs))
59 # try:
60 # list.append(list.pop(list.index(key)))
61 # except ValueError:
62 # dict[key] = function(*args, **kwargs)
63 # list.append(key)
64 # if limit is not None and len(list) > limit:
65 # del dict[list.pop(0)]
67 # return dict[key]
69 # memoize_wrapper._memoize_dict = dict
70 # memoize_wrapper._memoize_list = list
71 # memoize_wrapper._memoize_limit = limit
72 # memoize_wrapper._memoize_origfunc = function
73 # memoize_wrapper.func_name = function.func_name
74 # return memoize_wrapper
78 #@memoized
79 #def fibonacci(n):
80 # "Return the nth fibonacci number."
81 # print n
82 # if n in (0, 1):
83 # return n
84 # val = fibonacci(n-1) + fibonacci(n-2)
85 # return val#
87 #fibonacci(5)
88 #fibonacci(12)