Package gofer :: Module collator
[hide private]
[frames] | no frames]

Source Code for Module gofer.collator

  1  # 
  2  # Copyright (c) 2011 Red Hat, Inc. 
  3  # 
  4  # This software is licensed to you under the GNU Lesser General Public 
  5  # License as published by the Free Software Foundation; either version 
  6  # 2 of the License (LGPLv2) or (at your option) any later version. 
  7  # There is NO WARRANTY for this software, express or implied, 
  8  # including the implied warranties of MERCHANTABILITY, 
  9  # NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should 
 10  # have received a copy of LGPLv2 along with this software; if not, see 
 11  # http://www.gnu.org/licenses/old-licenses/lgpl-2.0.txt. 
 12  # 
 13  # Jeff Ortel <jortel@redhat.com> 
 14  # 
 15   
 16  """ 
 17  Provides decorator collator classes. 
 18  """ 
 19   
 20  import inspect 
 21   
 22   
23 -class Collator:
24 """ 25 Docorated method/function collator. 26 """ 27
28 - def collate(self, functions):
29 """ 30 Collate decorated functions/methods. 31 Returns (Classes, Unbound) where: 32 - Classes is: dict {class:[methods,..]} 33 - Unbound is: dict {module: [functions,...]} 34 @param functions: A collection of decorated functions. 35 @type functions: (list|dict) 36 @return: A tuple (classes, unbound) 37 @rtype: tuple(2) 38 """ 39 self.classes = {} 40 self.bound = set() 41 self.functions = functions 42 mapped = [] 43 for fn in functions: 44 g = fn.func_globals 45 if g in mapped: 46 continue 47 self.__map(g) 48 mapped.append(g) 49 return (self.classes, self.__functions())
50
51 - def __map(self, g):
52 for cls in self.__classes(g): 53 for method in self.__methods(cls): 54 fn = self.__function(method) 55 decorated = self.__decorated(fn) 56 if not decorated: 57 continue 58 self.bound.add(fn) 59 methods = self.__find(cls) 60 methods.append((method, decorated[1]))
61
62 - def __find(self, cls):
63 methods = self.classes.get(cls) 64 if methods is None: 65 methods = [] 66 self.classes[cls] = methods 67 return methods
68
69 - def __classes(self, g):
70 classes = [] 71 for x in g.values(): 72 if inspect.isclass(x): 73 classes.append(x) 74 return classes
75
76 - def __methods(self, cls):
77 return [v for n,v in \ 78 inspect.getmembers(cls, inspect.ismethod)]
79
80 - def __function(self, method):
81 for n,v in inspect.getmembers(method, inspect.isfunction): 82 return v
83
84 - def __functions(self):
85 modules = {} 86 for fn in self.functions: 87 if fn in self.bound: 88 continue 89 mod = inspect.getmodule(fn) 90 functions = modules.get(mod) 91 if not functions: 92 functions = [] 93 modules[mod] = functions 94 functions.append(self.__decorated(fn)) 95 return modules
96
97 - def __decorated(self, fn):
98 if fn in self.functions: 99 if isinstance(self.functions, dict): 100 return (fn, self.functions[fn]) 101 else: 102 return (fn, None)
103