summaryrefslogtreecommitdiff
path: root/interface.py
diff options
context:
space:
mode:
authorSylvain <syt@logilab.fr>2007-09-28 16:44:00 +0200
committerSylvain <syt@logilab.fr>2007-09-28 16:44:00 +0200
commitdb7bde02faf4be871a20e04cd78478304856d87e (patch)
tree19960fe5cd8153ef09a52db8ea46e0e55c6736f0 /interface.py
parent1f4776d70ecd6ac849e8e13c7ee9d8724d6e8787 (diff)
downloadlogilab-common-db7bde02faf4be871a20e04cd78478304856d87e.tar.gz
new extend function
Diffstat (limited to 'interface.py')
-rw-r--r--interface.py44
1 files changed, 34 insertions, 10 deletions
diff --git a/interface.py b/interface.py
index e94df1b..78f0afa 100644
--- a/interface.py
+++ b/interface.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2000-2004 LOGILAB S.A. (Paris, FRANCE).
+# Copyright (c) 2002-2007 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
@@ -14,7 +14,7 @@
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""
- bases class for interfaces
+ bases class for interfaces to provide "light" interface handling.
TODO:
_ implements a check method which check that an object implements the
@@ -31,15 +31,39 @@ class Interface:
def is_implemented_by(cls, instance):
return implements(instance, cls)
is_implemented_by = classmethod(is_implemented_by)
+
-def implements(instance, interface):
- """return true if the instance implements the interface
+def implements(obj, interface):
+ """return true if the give object (maybe an instance or class) implements
+ the interface
"""
- if hasattr(instance, "__implements__") and \
- (interface is instance.__implements__ or
- (type(instance.__implements__) in (ListType, TupleType) and \
- interface in instance.__implements__)):
- return 1
- return 0
+ kimplements = getattr(obj, '__implements__', ())
+ if not isinstance(kimplements, (list, tuple)):
+ kimplements = (kimplements,)
+ for implementedinterface in kimplements:
+ if issubclass(interface, implementedinterface):
+ return True
+ return False
+
+def extend(klass, interface, _recurs=False):
+ """add interface to klass'__implements__ if not already implemented in.
+ if klass is subclassed, ensure subclasses __implements__ it as well.
+
+ NOTE: klass should be e new class.
+ """
+ if not implements(klass, interface):
+ try:
+ kimplements = klass.__implements__
+ kimplementsklass = type(kimplements)
+ kimplements = list(kimplements)
+ except AttributeError:
+ kimplements = []
+ kimplements.append(interface)
+ klass.__implements__ = kimplementsklass(kimplements)
+ for subklass in klass.__subclasses__():
+ extend(subklass, interface, _recurs=True)
+ elif _recurs:
+ for subklass in klass.__subclasses__():
+ extend(subklass, interface, _recurs=True)