##// END OF EJS Templates
Minor doc updates.
Brian Granger -
Show More
@@ -1,221 +1,229 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 A lightweight component system for IPython.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10 """
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Copyright (C) 2008-2009 The IPython Development Team
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22
23 23 from copy import deepcopy
24 24 from weakref import WeakValueDictionary
25 25
26 26 from IPython.utils.ipstruct import Struct
27 27 from IPython.utils.traitlets import (
28 28 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
29 29 )
30 30
31 31
32 32 #-----------------------------------------------------------------------------
33 33 # Helper classes for Components
34 34 #-----------------------------------------------------------------------------
35 35
36 36
37 37 class ComponentError(Exception):
38 38 pass
39 39
40 40 class MetaComponentTracker(type):
41 41 """A metaclass that tracks instances of Components and its subclasses."""
42 42
43 43 def __init__(cls, name, bases, d):
44 44 super(MetaComponentTracker, cls).__init__(name, bases, d)
45 45 cls.__instance_refs = WeakValueDictionary()
46 46 cls.__numcreated = 0
47 47
48 48 def __call__(cls, *args, **kw):
49 49 """Called when *class* is called (instantiated)!!!
50 50
51 51 When a Component or subclass is instantiated, this is called and
52 52 the instance is saved in a WeakValueDictionary for tracking.
53 53 """
54 54
55 55 instance = super(MetaComponentTracker, cls).__call__(*args, **kw)
56 56 for c in cls.__mro__:
57 57 if issubclass(cls, c) and issubclass(c, Component):
58 58 c.__numcreated += 1
59 59 c.__instance_refs[c.__numcreated] = instance
60 60 return instance
61 61
62 62 def get_instances(cls, name=None, root=None):
63 63 """Get all instances of cls and its subclasses.
64 64
65 65 Parameters
66 66 ----------
67 67 name : str
68 68 Limit to components with this name.
69 69 root : Component or subclass
70 70 Limit to components having this root.
71 71 """
72 72 instances = cls.__instance_refs.values()
73 73 if name is not None:
74 74 instances = [i for i in instances if i.name == name]
75 75 if root is not None:
76 76 instances = [i for i in instances if i.root == root]
77 77 return instances
78 78
79 79 def get_instances_by_condition(cls, call, name=None, root=None):
80 80 """Get all instances of cls, i such that call(i)==True.
81 81
82 82 This also takes the ``name`` and ``root`` arguments of
83 83 :meth:`get_instance`
84 84 """
85 85 return [i for i in cls.get_instances(name, root) if call(i)]
86 86
87 87
88 88 class ComponentNameGenerator(object):
89 89 """A Singleton to generate unique component names."""
90 90
91 91 def __init__(self, prefix):
92 92 self.prefix = prefix
93 93 self.i = 0
94 94
95 95 def __call__(self):
96 96 count = self.i
97 97 self.i += 1
98 98 return "%s%s" % (self.prefix, count)
99 99
100 100
101 101 ComponentNameGenerator = ComponentNameGenerator('ipython.component')
102 102
103 103
104 104 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
105 105 pass
106 106
107 107
108 108 #-----------------------------------------------------------------------------
109 109 # Component implementation
110 110 #-----------------------------------------------------------------------------
111 111
112 112
113 113 class Component(HasTraitlets):
114 114
115 115 __metaclass__ = MetaComponent
116 116
117 117 # Traitlets are fun!
118 118 config = Instance(Struct,(),{})
119 119 parent = This()
120 120 root = This()
121 121
122 122 def __init__(self, parent, name=None, config=None):
123 123 """Create a component given a parent and possibly and name and config.
124 124
125 125 Parameters
126 126 ----------
127 127 parent : Component subclass
128 128 The parent in the component graph. The parent is used
129 129 to get the root of the component graph.
130 130 name : str
131 131 The unique name of the component. If empty, then a unique
132 132 one will be autogenerated.
133 133 config : Struct
134 134 If this is empty, self.config = parent.config, otherwise
135 135 self.config = config and root.config is ignored. This argument
136 136 should only be used to *override* the automatic inheritance of
137 137 parent.config. If a caller wants to modify parent.config
138 138 (not override), the caller should make a copy and change
139 139 attributes and then pass the copy to this argument.
140 140
141 141 Notes
142 142 -----
143 143 Subclasses of Component must call the :meth:`__init__` method of
144 144 :class:`Component` *before* doing anything else and using
145 145 :func:`super`::
146 146
147 147 class MyComponent(Component):
148 148 def __init__(self, parent, name=None, config=None):
149 149 super(MyComponent, self).__init__(parent, name, config)
150 150 # Then any other code you need to finish initialization.
151 151
152 152 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
153 153 attributes are handled properly.
154 154 """
155 155 super(Component, self).__init__()
156 156 self._children = []
157 157 if name is None:
158 158 self.name = ComponentNameGenerator()
159 159 else:
160 160 self.name = name
161 161 self.root = self # This is the default, it is set when parent is set
162 162 self.parent = parent
163 163 if config is not None:
164 164 self.config = deepcopy(config)
165 165 else:
166 166 if self.parent is not None:
167 167 self.config = deepcopy(self.parent.config)
168 168
169 169 #-------------------------------------------------------------------------
170 170 # Static traitlet notifiations
171 171 #-------------------------------------------------------------------------
172 172
173 173 def _parent_changed(self, name, old, new):
174 174 if old is not None:
175 175 old._remove_child(self)
176 176 if new is not None:
177 177 new._add_child(self)
178 178
179 179 if new is None:
180 180 self.root = self
181 181 else:
182 182 self.root = new.root
183 183
184 184 def _root_changed(self, name, old, new):
185 185 if self.parent is None:
186 186 if not (new is self):
187 187 raise ComponentError("Root not self, but parent is None.")
188 188 else:
189 189 if not self.parent.root is new:
190 190 raise ComponentError("Error in setting the root attribute: "
191 191 "root != parent.root")
192 192
193 193 def _config_changed(self, name, old, new):
194 """Update all the class traits having a config_key with the config.
195
196 For any class traitlet with a ``config_key`` metadata attribute, we
197 update the traitlet with the value of the corresponding config entry.
198
199 In the future, we might want to do a pop here so stale config info
200 is not passed onto children.
201 """
194 202 # Get all traitlets with a config_key metadata entry
195 203 traitlets = self.traitlets('config_key')
196 204 for k, v in traitlets.items():
197 205 try:
198 206 config_value = new[v.get_metadata('config_key')]
199 207 except KeyError:
200 208 pass
201 209 else:
202 210 setattr(self, k, config_value)
203 211
204 212 @property
205 213 def children(self):
206 214 """A list of all my child components."""
207 215 return self._children
208 216
209 217 def _remove_child(self, child):
210 218 """A private method for removing children components."""
211 219 if child in self._children:
212 220 index = self._children.index(child)
213 221 del self._children[index]
214 222
215 223 def _add_child(self, child):
216 224 """A private method for adding children components."""
217 225 if child not in self._children:
218 226 self._children.append(child)
219 227
220 228 def __repr__(self):
221 229 return "<Component('%s')>" % self.name
General Comments 0
You need to be logged in to leave comments. Login now