comparison pyikriam/utils.py @ 160:7551342718b6

Refactory pyikriam with patterns. - Use dyna_prog, a dynamic programming decorator, to cache city objects. - fake_moz to emulate a mozilla browser.
author Thinker K.F. Li <thinker@branda.to>
date Sat, 01 Nov 2008 21:29:51 +0800
parents
children
comparison
equal deleted inserted replaced
159:e2956846ee98 160:7551342718b6
1 ## \brief decorator is a class decorate another of another object.
2 #
3 # Access of attributes/methods that can not be found in an instance
4 # of a class of this meta-class, decorator, are delegated to the backend
5 # of the instance.
6 #
7 # A backend object always passed as first parameter when
8 # instantiate an instance of a class with decorator as meta-class.
9 # For example,
10 # \code
11 # class foo(object):
12 # __metaclass__ = decorator
13 #
14 # backend.data = 3
15 # obj = foo(backend)
16 # print obj.data
17 # backend.data = 4
18 # print obj.data
19 # \endcode
20 # it print out 3 and 4 respectively.
21 #
22 class decorator(type):
23 def __init__(clz, name, base, dict):
24 super(decorator, clz).__init__(name, base, dict)
25 clz.__getattr__ = decorator.__dele_getattr
26 pass
27
28 @staticmethod
29 def set_backend(obj, backend):
30 obj.__backend = backend
31 pass
32
33 @staticmethod
34 def __dele_getattr(obj, name):
35 return getattr(obj.__backend, name)
36 pass
37
38
39 ## \brief Decorator to make functions or methods dynamic programming.
40 #
41 # dyna_prog result of functions or methods with their arguments as key.
42 # It supposes result of a function always the same if the same arguments
43 # are passed. It cache result of cached function to avoid really calling
44 # function every time.
45 class dyna_prog(object):
46 class functor(object):
47 def __init__(self, instance, method):
48 self._method = method
49 self._instance = instance
50 self._cache = {}
51 pass
52
53 def __call__(self, *args):
54 try:
55 return self._cache[args]
56 except KeyError:
57 pass
58 instance = self._instance
59 result = self._method(instance, *args)
60 return self._cache.setdefault(args, result)
61
62 def clear(self):
63 self._cache.clear()
64 pass
65
66 def __init__(self, method):
67 super(dyna_prog, self).__init__()
68 self._method = method
69 self._functors = {}
70 pass
71
72 def __get__(self, instance, owner):
73 try:
74 return self._functors[instance]
75 except KeyError:
76 pass
77 functor_o = dyna_prog.functor(instance, self._method)
78 return self._functors.setdefault(instance, functor_o)
79 pass
80