root / logilab.pylintinstaller / logilab / common / interface.py

Revision 202:d67e86292521, 2.5 kB (checked in by tziade@…, 9 months ago)

added logilab.pylintinstaller

Line 
1# Copyright (c) 2002-2007 LOGILAB S.A. (Paris, FRANCE).
2# http://www.logilab.fr/ -- mailto:contact@logilab.fr
3#
4# This program is free software; you can redistribute it and/or modify it under
5# the terms of the GNU General Public License as published by the Free Software
6# Foundation; either version 2 of the License, or (at your option) any later
7# version.
8#
9# This program is distributed in the hope that it will be useful, but WITHOUT
10# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License along with
14# this program; if not, write to the Free Software Foundation, Inc.,
15# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
16"""
17 bases class for interfaces to provide "light" interface handling.
18
19 TODO:
20  _ implements a check method which check that an object implements the
21    interface
22  _ Attribute objects
23
24  This module requires at least python 2.2
25"""
26
27from types import ListType, TupleType
28
29class Interface:
30    """base class for interfaces"""
31    def is_implemented_by(cls, instance):
32        return implements(instance, cls)
33    is_implemented_by = classmethod(is_implemented_by)
34
35   
36def implements(obj, interface):
37    """return true if the give object (maybe an instance or class) implements
38    the interface
39    """
40    kimplements = getattr(obj, '__implements__', ())
41    if not isinstance(kimplements, (list, tuple)):
42        kimplements = (kimplements,)
43    for implementedinterface in kimplements:
44        if issubclass(implementedinterface, interface):
45            return True
46    return False
47
48
49def extend(klass, interface, _recurs=False):
50    """add interface to klass'__implements__ if not already implemented in.
51
52    if klass is subclassed, ensure subclasses __implements__ it as well.
53   
54    NOTE: klass should be e new class.
55    """
56    if not implements(klass, interface):
57        try:
58            kimplements = klass.__implements__
59            kimplementsklass = type(kimplements)
60            kimplements = list(kimplements)
61        except AttributeError:
62            kimplementsklass = tuple
63            kimplements = []
64        kimplements.append(interface)
65        klass.__implements__ = kimplementsklass(kimplements)
66        for subklass in klass.__subclasses__():
67            extend(subklass, interface, _recurs=True)
68    elif _recurs:
69        for subklass in klass.__subclasses__():
70            extend(subklass, interface, _recurs=True)
Note: See TracBrowser for help on using the browser.