Package kenozooid :: Module component

Source Code for Module kenozooid.component

  1  # 
  2  # Kenozooid - dive planning and analysis toolbox. 
  3  # 
  4  # Copyright (C) 2009-2019 by Artur Wroblewski <wrobell@riseup.net> 
  5  # 
  6  # This program is free software: you can redistribute it and/or modify 
  7  # it under the terms of the GNU General Public License as published by 
  8  # the Free Software Foundation, either version 3 of the License, or 
  9  # (at your option) any later version. 
 10  # 
 11  # This program is distributed in the hope that it will be useful, 
 12  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 13  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 14  # GNU General Public License for more details. 
 15  # 
 16  # You should have received a copy of the GNU General Public License 
 17  # along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 18  # 
 19   
 20  """ 
 21  Simple component interface injection and component repository querying 
 22  mechanism. 
 23  """ 
 24   
 25  import itertools 
 26  ichain = itertools.chain.from_iterable 
 27  import logging 
 28   
 29  log = logging.getLogger('kenozooid.component') 
 30   
 31  # component registry 
 32  _registry = {} 
 33   
34 -def inject(iface, **params):
35 """ 36 Class decorator to declare interface implementation. 37 38 Injection parameters can be used to query for classes implementing an 39 interface and having appropriate values. 40 41 :Parameters: 42 iface 43 Interface to inject. 44 params 45 Injection parameters. 46 """ 47 def f(cls): 48 log.debug('inject interface %s for class %s with params %s' \ 49 % (iface.__name__, cls.__name__, params)) 50 51 if iface not in _registry: 52 _registry[iface] = [] 53 _registry[iface].append((cls, params)) 54 55 return cls
56 57 return f 58 59
60 -def _applies(p1, p2):
61 """ 62 Check if values stored in two dictionaries are equal for all keys 63 stored in first dictionary. 64 65 :Parameters: 66 p1 67 First dictionary. 68 p2 69 Second dictionary. 70 """ 71 keys = set(p2.keys()) 72 return all(k in keys and p1[k] == p2[k] for k in p1.keys())
73 74
75 -def query(iface=None, **params):
76 """ 77 Look for class implementing specified interface. 78 """ 79 if iface is None: 80 data = ichain(_registry.values()) 81 elif iface in _registry: 82 data = _registry[iface] 83 else: 84 data = () 85 86 return (cls for cls, p in data if _applies(params, p))
87 88
89 -def params(cls):
90 """ 91 Get interface injection parameters for component realized with 92 specified class. 93 94 :Parameters: 95 cls 96 Class realizing component. 97 """ 98 for c, p in ichain(_registry.values()): 99 if c == cls: 100 return p
101 102 103 # vim: sw=4:et:ai 104