Package logilab :: Package common :: Module interface
[frames] | no frames]

Source Code for Module logilab.common.interface

 1  # copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. 
 2  # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr 
 3  # 
 4  # This file is part of logilab-common. 
 5  # 
 6  # logilab-common is free software: you can redistribute it and/or modify it under 
 7  # the terms of the GNU Lesser General Public License as published by the Free 
 8  # Software Foundation, either version 2.1 of the License, or (at your option) any 
 9  # later version. 
10  # 
11  # logilab-common is distributed in the hope that it will be useful, but WITHOUT 
12  # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
13  # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more 
14  # details. 
15  # 
16  # You should have received a copy of the GNU Lesser General Public License along 
17  # with logilab-common.  If not, see <http://www.gnu.org/licenses/>. 
18  """Bases class for interfaces to provide 'light' interface handling. 
19   
20   TODO: 
21    _ implements a check method which check that an object implements the 
22      interface 
23    _ Attribute objects 
24   
25    This module requires at least python 2.2 
26   
27   
28   
29   
30  """ 
31  __docformat__ = "restructuredtext en" 
32   
33  from types import ListType, TupleType 
34   
35 -class Interface(object):
36 """Base class for interfaces."""
37 - def is_implemented_by(cls, instance):
38 return implements(instance, cls)
39 is_implemented_by = classmethod(is_implemented_by)
40 41
42 -def implements(obj, interface):
43 """Return true if the give object (maybe an instance or class) implements 44 the interface. 45 """ 46 kimplements = getattr(obj, '__implements__', ()) 47 if not isinstance(kimplements, (list, tuple)): 48 kimplements = (kimplements,) 49 for implementedinterface in kimplements: 50 if issubclass(implementedinterface, interface): 51 return True 52 return False
53 54
55 -def extend(klass, interface, _recurs=False):
56 """Add interface to klass'__implements__ if not already implemented in. 57 58 If klass is subclassed, ensure subclasses __implements__ it as well. 59 60 NOTE: klass should be e new class. 61 """ 62 if not implements(klass, interface): 63 try: 64 kimplements = klass.__implements__ 65 kimplementsklass = type(kimplements) 66 kimplements = list(kimplements) 67 except AttributeError: 68 kimplementsklass = tuple 69 kimplements = [] 70 kimplements.append(interface) 71 klass.__implements__ = kimplementsklass(kimplements) 72 for subklass in klass.__subclasses__(): 73 extend(subklass, interface, _recurs=True) 74 elif _recurs: 75 for subklass in klass.__subclasses__(): 76 extend(subklass, interface, _recurs=True)
77