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

Source Code for Module common.interface

 1  # copyright 2003-2011 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  __docformat__ = "restructuredtext en" 
28   
29   
30 -class Interface(object):
31 """Base class for interfaces."""
32 - def is_implemented_by(cls, instance):
33 return implements(instance, cls)
34 is_implemented_by = classmethod(is_implemented_by)
35 36
37 -def implements(obj, interface):
38 """Return true if the give object (maybe an instance or class) implements 39 the interface. 40 """ 41 kimplements = getattr(obj, '__implements__', ()) 42 if not isinstance(kimplements, (list, tuple)): 43 kimplements = (kimplements,) 44 for implementedinterface in kimplements: 45 if issubclass(implementedinterface, interface): 46 return True 47 return False
48 49
50 -def extend(klass, interface, _recurs=False):
51 """Add interface to klass'__implements__ if not already implemented in. 52 53 If klass is subclassed, ensure subclasses __implements__ it as well. 54 55 NOTE: klass should be e new class. 56 """ 57 if not implements(klass, interface): 58 try: 59 kimplements = klass.__implements__ 60 kimplementsklass = type(kimplements) 61 kimplements = list(kimplements) 62 except AttributeError: 63 kimplementsklass = tuple 64 kimplements = [] 65 kimplements.append(interface) 66 klass.__implements__ = kimplementsklass(kimplements) 67 for subklass in klass.__subclasses__(): 68 extend(subklass, interface, _recurs=True) 69 elif _recurs: 70 for subklass in klass.__subclasses__(): 71 extend(subklass, interface, _recurs=True)
72