hooke.ui.gui was getting complicated, so I stripped it down for a moment.
[hooke.git] / hooke / util / pluggable.py
1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of Hooke.
4 #
5 # Hooke is free software: you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation, either
8 # version 3 of the License, or (at your option) any later version.
9 #
10 # Hooke is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke.  If not, see
17 # <http://www.gnu.org/licenses/>.
18
19 """`pluggable`
20 """
21
22 from ..compat.odict import odict
23 from .graph import Node, Graph
24
25
26 class IsSubclass (object):
27     """A safe subclass comparator.
28     
29     Examples
30     --------
31
32     >>> class A (object):
33     ...     pass
34     >>> class B (A):
35     ...     pass
36     >>> C = 5
37     >>> is_subclass = IsSubclass(A)
38     >>> is_subclass(A)
39     True
40     >>> is_subclass = IsSubclass(A, blacklist=[A])
41     >>> is_subclass(A)
42     False
43     >>> is_subclass(B)
44     True
45     >>> is_subclass(C)
46     False
47     """
48     def __init__(self, base_class, blacklist=None):
49         self.base_class = base_class
50         if blacklist == None:
51             blacklist = []
52         self.blacklist = blacklist
53     def __call__(self, other):
54         try:
55             subclass = issubclass(other, self.base_class)
56         except TypeError:
57             return False
58         if other in self.blacklist:
59             return False
60         return subclass
61
62
63 def construct_odict(this_modname, submodnames, class_selector,
64                     instantiate=True):
65     """Search the submodules `submodnames` of a module `this_modname`
66     for class objects for which `class_selector(class)` returns
67     `True`.  If `instantiate == True` these classes are instantiated
68     and stored in the returned :class:`hooke.compat.odict.odict` in
69     the order in which they were discovered.  Otherwise, the class
70     itself is stored.
71     """
72     objs = odict()
73     for submodname in submodnames:
74         count = len([s for s in submodnames if s == submodname])
75         assert count > 0, 'No %s entries: %s' % (submodname, submodnames)
76         assert count == 1, 'Multiple (%d) %s entries: %s' \
77             % (count, submodname, submodnames)
78         this_mod = __import__(this_modname, fromlist=[submodname])
79         submod = getattr(this_mod, submodname)
80         for objname in dir(submod):
81             obj = getattr(submod, objname)
82             if class_selector(obj):
83                 if instantiate == True:
84                     obj = obj()
85                 name = getattr(obj, 'name', submodname)
86                 objs[name] = obj
87     return objs
88
89
90 def construct_graph(this_modname, submodnames, class_selector,
91                     assert_name_match=True):
92     """Search the submodules `submodnames` of a module `this_modname`
93     for class objects for which `class_selector(class)` returns
94     `True`.  These classes are instantiated, and the `instance.name`
95     is compared to the `submodname` (if `assert_name_match` is
96     `True`).
97
98     The instances are further arranged into a dependency
99     :class:`hooke.util.graph.Graph` according to their
100     `instance.dependencies()` values.  The topologically sorted graph
101     is returned.
102     """
103     instances = {}
104     for submodname in submodnames:
105         count = len([s for s in submodnames if s == submodname])
106         assert count > 0, 'No %s entries: %s' % (submodname, submodnames)
107         assert count == 1, 'Multiple (%d) %s entries: %s' \
108             % (count, submodname, submodnames)
109         this_mod = __import__(this_modname, fromlist=[submodname])
110         submod = getattr(this_mod, submodname)
111         for objname in dir(submod):
112             obj = getattr(submod, objname)
113             if class_selector(obj):
114                 instance = obj()
115                 if assert_name_match == True and instance.name != submodname:
116                     raise Exception(
117                         'Instance name %s does not match module name %s'
118                         % (instance.name, submodname))
119                 instances[instance.name] = instance
120     nodes = {}
121     for i in instances.values():     # make nodes for each instance
122         nodes[i.name] = Node(data=i)
123     for n in nodes.values():         # fill in dependencies for each node
124         n.extend([nodes[name] for name in n.data.dependencies()])
125     graph = Graph(nodes.values())
126     graph.topological_sort()
127     return graph