Show More
@@ -1,337 +1,346 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | A lightweight component system for IPython. |
|
4 | A lightweight component system for IPython. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Imports |
|
20 | # Imports | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | from copy import deepcopy |
|
23 | from copy import deepcopy | |
24 | import datetime |
|
24 | import datetime | |
25 | from weakref import WeakValueDictionary |
|
25 | from weakref import WeakValueDictionary | |
26 |
|
26 | |||
27 | from IPython.utils.importstring import import_item |
|
27 | from IPython.utils.importstring import import_item | |
28 | from IPython.config.loader import Config |
|
28 | from IPython.config.loader import Config | |
29 | from IPython.utils.traitlets import ( |
|
29 | from IPython.utils.traitlets import ( | |
30 | HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This |
|
30 | HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This | |
31 | ) |
|
31 | ) | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # Helper classes for Components |
|
35 | # Helper classes for Components | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | class ComponentError(Exception): |
|
39 | class ComponentError(Exception): | |
40 | pass |
|
40 | pass | |
41 |
|
41 | |||
42 | class MetaComponentTracker(type): |
|
42 | class MetaComponentTracker(type): | |
43 | """A metaclass that tracks instances of Components and its subclasses.""" |
|
43 | """A metaclass that tracks instances of Components and its subclasses.""" | |
44 |
|
44 | |||
45 | def __init__(cls, name, bases, d): |
|
45 | def __init__(cls, name, bases, d): | |
46 | super(MetaComponentTracker, cls).__init__(name, bases, d) |
|
46 | super(MetaComponentTracker, cls).__init__(name, bases, d) | |
47 | cls.__instance_refs = WeakValueDictionary() |
|
47 | cls.__instance_refs = WeakValueDictionary() | |
48 | cls.__numcreated = 0 |
|
48 | cls.__numcreated = 0 | |
49 |
|
49 | |||
50 | def __call__(cls, *args, **kw): |
|
50 | def __call__(cls, *args, **kw): | |
51 | """Called when a class is called (instantiated)!!! |
|
51 | """Called when a class is called (instantiated)!!! | |
52 |
|
52 | |||
53 | When a Component or subclass is instantiated, this is called and |
|
53 | When a Component or subclass is instantiated, this is called and | |
54 | the instance is saved in a WeakValueDictionary for tracking. |
|
54 | the instance is saved in a WeakValueDictionary for tracking. | |
55 | """ |
|
55 | """ | |
56 | instance = cls.__new__(cls, *args, **kw) |
|
56 | instance = cls.__new__(cls, *args, **kw) | |
57 |
|
57 | |||
58 | # Register the instance before __init__ is called so get_instances |
|
58 | # Register the instance before __init__ is called so get_instances | |
59 | # works inside __init__ methods! |
|
59 | # works inside __init__ methods! | |
60 | indices = cls.register_instance(instance) |
|
60 | indices = cls.register_instance(instance) | |
61 |
|
61 | |||
62 | # This is in a try/except because of the __init__ method fails, the |
|
62 | # This is in a try/except because of the __init__ method fails, the | |
63 | # instance is discarded and shouldn't be tracked. |
|
63 | # instance is discarded and shouldn't be tracked. | |
64 | try: |
|
64 | try: | |
65 | if isinstance(instance, cls): |
|
65 | if isinstance(instance, cls): | |
66 | cls.__init__(instance, *args, **kw) |
|
66 | cls.__init__(instance, *args, **kw) | |
67 | except: |
|
67 | except: | |
68 | # Unregister the instance because __init__ failed! |
|
68 | # Unregister the instance because __init__ failed! | |
69 | cls.unregister_instances(indices) |
|
69 | cls.unregister_instances(indices) | |
70 | raise |
|
70 | raise | |
71 | else: |
|
71 | else: | |
72 | return instance |
|
72 | return instance | |
73 |
|
73 | |||
74 | def register_instance(cls, instance): |
|
74 | def register_instance(cls, instance): | |
75 | """Register instance with cls and its subclasses.""" |
|
75 | """Register instance with cls and its subclasses.""" | |
76 | # indices is a list of the keys used to register the instance |
|
76 | # indices is a list of the keys used to register the instance | |
77 | # with. This list is needed if the instance needs to be unregistered. |
|
77 | # with. This list is needed if the instance needs to be unregistered. | |
78 | indices = [] |
|
78 | indices = [] | |
79 | for c in cls.__mro__: |
|
79 | for c in cls.__mro__: | |
80 | if issubclass(cls, c) and issubclass(c, Component): |
|
80 | if issubclass(cls, c) and issubclass(c, Component): | |
81 | c.__numcreated += 1 |
|
81 | c.__numcreated += 1 | |
82 | indices.append(c.__numcreated) |
|
82 | indices.append(c.__numcreated) | |
83 | c.__instance_refs[c.__numcreated] = instance |
|
83 | c.__instance_refs[c.__numcreated] = instance | |
84 | else: |
|
84 | else: | |
85 | break |
|
85 | break | |
86 | return indices |
|
86 | return indices | |
87 |
|
87 | |||
88 | def unregister_instances(cls, indices): |
|
88 | def unregister_instances(cls, indices): | |
89 | """Unregister instance with cls and its subclasses.""" |
|
89 | """Unregister instance with cls and its subclasses.""" | |
90 | for c, index in zip(cls.__mro__, indices): |
|
90 | for c, index in zip(cls.__mro__, indices): | |
91 | try: |
|
91 | try: | |
92 | del c.__instance_refs[index] |
|
92 | del c.__instance_refs[index] | |
93 | except KeyError: |
|
93 | except KeyError: | |
94 | pass |
|
94 | pass | |
95 |
|
95 | |||
96 | def clear_instances(cls): |
|
96 | def clear_instances(cls): | |
97 | """Clear all instances tracked by cls.""" |
|
97 | """Clear all instances tracked by cls.""" | |
98 | cls.__instance_refs.clear() |
|
98 | cls.__instance_refs.clear() | |
99 | cls.__numcreated = 0 |
|
99 | cls.__numcreated = 0 | |
100 |
|
100 | |||
101 | def get_instances(cls, name=None, root=None, klass=None): |
|
101 | def get_instances(cls, name=None, root=None, klass=None): | |
102 | """Get all instances of cls and its subclasses. |
|
102 | """Get all instances of cls and its subclasses. | |
103 |
|
103 | |||
104 | Parameters |
|
104 | Parameters | |
105 | ---------- |
|
105 | ---------- | |
106 | name : str |
|
106 | name : str | |
107 | Limit to components with this name. |
|
107 | Limit to components with this name. | |
108 | root : Component or subclass |
|
108 | root : Component or subclass | |
109 | Limit to components having this root. |
|
109 | Limit to components having this root. | |
110 | klass : class or str |
|
110 | klass : class or str | |
111 | Limits to instances of the class or its subclasses. If a str |
|
111 | Limits to instances of the class or its subclasses. If a str | |
112 | is given ut must be in the form 'foo.bar.MyClass'. The str |
|
112 | is given ut must be in the form 'foo.bar.MyClass'. The str | |
113 | form of this argument is useful for forward declarations. |
|
113 | form of this argument is useful for forward declarations. | |
114 | """ |
|
114 | """ | |
115 | if klass is not None: |
|
115 | if klass is not None: | |
116 | if isinstance(klass, basestring): |
|
116 | if isinstance(klass, basestring): | |
117 | klass = import_item(klass) |
|
117 | klass = import_item(klass) | |
118 | # Limit search to instances of klass for performance |
|
118 | # Limit search to instances of klass for performance | |
119 | if issubclass(klass, Component): |
|
119 | if issubclass(klass, Component): | |
120 | return klass.get_instances(name=name, root=root) |
|
120 | return klass.get_instances(name=name, root=root) | |
121 | instances = cls.__instance_refs.values() |
|
121 | instances = cls.__instance_refs.values() | |
122 | if name is not None: |
|
122 | if name is not None: | |
123 | instances = [i for i in instances if i.name == name] |
|
123 | instances = [i for i in instances if i.name == name] | |
124 | if klass is not None: |
|
124 | if klass is not None: | |
125 | instances = [i for i in instances if isinstance(i, klass)] |
|
125 | instances = [i for i in instances if isinstance(i, klass)] | |
126 | if root is not None: |
|
126 | if root is not None: | |
127 | instances = [i for i in instances if i.root == root] |
|
127 | instances = [i for i in instances if i.root == root] | |
128 | return instances |
|
128 | return instances | |
129 |
|
129 | |||
130 | def get_instances_by_condition(cls, call, name=None, root=None, |
|
130 | def get_instances_by_condition(cls, call, name=None, root=None, | |
131 | klass=None): |
|
131 | klass=None): | |
132 | """Get all instances of cls, i such that call(i)==True. |
|
132 | """Get all instances of cls, i such that call(i)==True. | |
133 |
|
133 | |||
134 | This also takes the ``name`` and ``root`` and ``classname`` |
|
134 | This also takes the ``name`` and ``root`` and ``classname`` | |
135 | arguments of :meth:`get_instance` |
|
135 | arguments of :meth:`get_instance` | |
136 | """ |
|
136 | """ | |
137 | return [i for i in cls.get_instances(name, root, klass) if call(i)] |
|
137 | return [i for i in cls.get_instances(name, root, klass) if call(i)] | |
138 |
|
138 | |||
139 |
|
139 | |||
140 | def masquerade_as(instance, cls): |
|
140 | def masquerade_as(instance, cls): | |
141 | """Let instance masquerade as an instance of cls. |
|
141 | """Let instance masquerade as an instance of cls. | |
142 |
|
142 | |||
143 | Sometimes, such as in testing code, it is useful to let a class |
|
143 | Sometimes, such as in testing code, it is useful to let a class | |
144 | masquerade as another. Python, being duck typed, allows this by |
|
144 | masquerade as another. Python, being duck typed, allows this by | |
145 | default. But, instances of components are tracked by their class type. |
|
145 | default. But, instances of components are tracked by their class type. | |
146 |
|
146 | |||
147 | After calling this, ``cls.get_instances()`` will return ``instance``. This |
|
147 | After calling this, ``cls.get_instances()`` will return ``instance``. This | |
148 | does not, however, cause ``isinstance(instance, cls)`` to return ``True``. |
|
148 | does not, however, cause ``isinstance(instance, cls)`` to return ``True``. | |
149 |
|
149 | |||
150 | Parameters |
|
150 | Parameters | |
151 | ---------- |
|
151 | ---------- | |
152 | instance : an instance of a Component or Component subclass |
|
152 | instance : an instance of a Component or Component subclass | |
153 | The instance that will pretend to be a cls. |
|
153 | The instance that will pretend to be a cls. | |
154 | cls : subclass of Component |
|
154 | cls : subclass of Component | |
155 | The Component subclass that instance will pretend to be. |
|
155 | The Component subclass that instance will pretend to be. | |
156 | """ |
|
156 | """ | |
157 | cls.register_instance(instance) |
|
157 | cls.register_instance(instance) | |
158 |
|
158 | |||
159 |
|
159 | |||
160 | class ComponentNameGenerator(object): |
|
160 | class ComponentNameGenerator(object): | |
161 | """A Singleton to generate unique component names.""" |
|
161 | """A Singleton to generate unique component names.""" | |
162 |
|
162 | |||
163 | def __init__(self, prefix): |
|
163 | def __init__(self, prefix): | |
164 | self.prefix = prefix |
|
164 | self.prefix = prefix | |
165 | self.i = 0 |
|
165 | self.i = 0 | |
166 |
|
166 | |||
167 | def __call__(self): |
|
167 | def __call__(self): | |
168 | count = self.i |
|
168 | count = self.i | |
169 | self.i += 1 |
|
169 | self.i += 1 | |
170 | return "%s%s" % (self.prefix, count) |
|
170 | return "%s%s" % (self.prefix, count) | |
171 |
|
171 | |||
172 |
|
172 | |||
173 | ComponentNameGenerator = ComponentNameGenerator('ipython.component') |
|
173 | ComponentNameGenerator = ComponentNameGenerator('ipython.component') | |
174 |
|
174 | |||
175 |
|
175 | |||
176 | class MetaComponent(MetaHasTraitlets, MetaComponentTracker): |
|
176 | class MetaComponent(MetaHasTraitlets, MetaComponentTracker): | |
177 | pass |
|
177 | pass | |
178 |
|
178 | |||
179 |
|
179 | |||
180 | #----------------------------------------------------------------------------- |
|
180 | #----------------------------------------------------------------------------- | |
181 | # Component implementation |
|
181 | # Component implementation | |
182 | #----------------------------------------------------------------------------- |
|
182 | #----------------------------------------------------------------------------- | |
183 |
|
183 | |||
184 |
|
184 | |||
185 | class Component(HasTraitlets): |
|
185 | class Component(HasTraitlets): | |
186 |
|
186 | |||
187 | __metaclass__ = MetaComponent |
|
187 | __metaclass__ = MetaComponent | |
188 |
|
188 | |||
189 | # Traitlets are fun! |
|
189 | # Traitlets are fun! | |
190 | config = Instance(Config,(),{}) |
|
190 | config = Instance(Config,(),{}) | |
191 | parent = This() |
|
191 | parent = This() | |
192 | root = This() |
|
192 | root = This() | |
193 | created = None |
|
193 | created = None | |
194 |
|
194 | |||
195 | def __init__(self, parent, name=None, config=None): |
|
195 | def __init__(self, parent, name=None, config=None): | |
196 | """Create a component given a parent and possibly and name and config. |
|
196 | """Create a component given a parent and possibly and name and config. | |
197 |
|
197 | |||
198 | Parameters |
|
198 | Parameters | |
199 | ---------- |
|
199 | ---------- | |
200 | parent : Component subclass |
|
200 | parent : Component subclass | |
201 | The parent in the component graph. The parent is used |
|
201 | The parent in the component graph. The parent is used | |
202 | to get the root of the component graph. |
|
202 | to get the root of the component graph. | |
203 | name : str |
|
203 | name : str | |
204 | The unique name of the component. If empty, then a unique |
|
204 | The unique name of the component. If empty, then a unique | |
205 | one will be autogenerated. |
|
205 | one will be autogenerated. | |
206 | config : Config |
|
206 | config : Config | |
207 | If this is empty, self.config = parent.config, otherwise |
|
207 | If this is empty, self.config = parent.config, otherwise | |
208 | self.config = config and root.config is ignored. This argument |
|
208 | self.config = config and root.config is ignored. This argument | |
209 | should only be used to *override* the automatic inheritance of |
|
209 | should only be used to *override* the automatic inheritance of | |
210 | parent.config. If a caller wants to modify parent.config |
|
210 | parent.config. If a caller wants to modify parent.config | |
211 | (not override), the caller should make a copy and change |
|
211 | (not override), the caller should make a copy and change | |
212 | attributes and then pass the copy to this argument. |
|
212 | attributes and then pass the copy to this argument. | |
213 |
|
213 | |||
214 | Notes |
|
214 | Notes | |
215 | ----- |
|
215 | ----- | |
216 | Subclasses of Component must call the :meth:`__init__` method of |
|
216 | Subclasses of Component must call the :meth:`__init__` method of | |
217 | :class:`Component` *before* doing anything else and using |
|
217 | :class:`Component` *before* doing anything else and using | |
218 | :func:`super`:: |
|
218 | :func:`super`:: | |
219 |
|
219 | |||
220 | class MyComponent(Component): |
|
220 | class MyComponent(Component): | |
221 | def __init__(self, parent, name=None, config=None): |
|
221 | def __init__(self, parent, name=None, config=None): | |
222 | super(MyComponent, self).__init__(parent, name, config) |
|
222 | super(MyComponent, self).__init__(parent, name, config) | |
223 | # Then any other code you need to finish initialization. |
|
223 | # Then any other code you need to finish initialization. | |
224 |
|
224 | |||
225 | This ensures that the :attr:`parent`, :attr:`name` and :attr:`config` |
|
225 | This ensures that the :attr:`parent`, :attr:`name` and :attr:`config` | |
226 | attributes are handled properly. |
|
226 | attributes are handled properly. | |
227 | """ |
|
227 | """ | |
228 | super(Component, self).__init__() |
|
228 | super(Component, self).__init__() | |
229 | self._children = [] |
|
229 | self._children = [] | |
230 | if name is None: |
|
230 | if name is None: | |
231 | self.name = ComponentNameGenerator() |
|
231 | self.name = ComponentNameGenerator() | |
232 | else: |
|
232 | else: | |
233 | self.name = name |
|
233 | self.name = name | |
234 | self.root = self # This is the default, it is set when parent is set |
|
234 | self.root = self # This is the default, it is set when parent is set | |
235 | self.parent = parent |
|
235 | self.parent = parent | |
236 | if config is not None: |
|
236 | if config is not None: | |
237 | self.config = config |
|
237 | self.config = config | |
238 | # We used to deepcopy, but for now we are trying to just save |
|
238 | # We used to deepcopy, but for now we are trying to just save | |
239 | # by reference. This *could* have side effects as all components |
|
239 | # by reference. This *could* have side effects as all components | |
240 | # will share config. |
|
240 | # will share config. In fact, I did find such a side effect in | |
|
241 | # _config_changed below. If a config attribute value was a mutable type | |||
|
242 | # all instances of a component were getting the same copy, effectively | |||
|
243 | # making that a class attribute. | |||
241 | # self.config = deepcopy(config) |
|
244 | # self.config = deepcopy(config) | |
242 | else: |
|
245 | else: | |
243 | if self.parent is not None: |
|
246 | if self.parent is not None: | |
244 | self.config = self.parent.config |
|
247 | self.config = self.parent.config | |
245 | # We used to deepcopy, but for now we are trying to just save |
|
248 | # We used to deepcopy, but for now we are trying to just save | |
246 | # by reference. This *could* have side effects as all components |
|
249 | # by reference. This *could* have side effects as all components | |
247 | # will share config. |
|
250 | # will share config. In fact, I did find such a side effect in | |
|
251 | # _config_changed below. If a config attribute value was a mutable type | |||
|
252 | # all instances of a component were getting the same copy, effectively | |||
|
253 | # making that a class attribute. | |||
248 | # self.config = deepcopy(self.parent.config) |
|
254 | # self.config = deepcopy(self.parent.config) | |
249 |
|
255 | |||
250 | self.created = datetime.datetime.now() |
|
256 | self.created = datetime.datetime.now() | |
251 |
|
257 | |||
252 | #------------------------------------------------------------------------- |
|
258 | #------------------------------------------------------------------------- | |
253 | # Static traitlet notifiations |
|
259 | # Static traitlet notifiations | |
254 | #------------------------------------------------------------------------- |
|
260 | #------------------------------------------------------------------------- | |
255 |
|
261 | |||
256 | def _parent_changed(self, name, old, new): |
|
262 | def _parent_changed(self, name, old, new): | |
257 | if old is not None: |
|
263 | if old is not None: | |
258 | old._remove_child(self) |
|
264 | old._remove_child(self) | |
259 | if new is not None: |
|
265 | if new is not None: | |
260 | new._add_child(self) |
|
266 | new._add_child(self) | |
261 |
|
267 | |||
262 | if new is None: |
|
268 | if new is None: | |
263 | self.root = self |
|
269 | self.root = self | |
264 | else: |
|
270 | else: | |
265 | self.root = new.root |
|
271 | self.root = new.root | |
266 |
|
272 | |||
267 | def _root_changed(self, name, old, new): |
|
273 | def _root_changed(self, name, old, new): | |
268 | if self.parent is None: |
|
274 | if self.parent is None: | |
269 | if not (new is self): |
|
275 | if not (new is self): | |
270 | raise ComponentError("Root not self, but parent is None.") |
|
276 | raise ComponentError("Root not self, but parent is None.") | |
271 | else: |
|
277 | else: | |
272 | if not self.parent.root is new: |
|
278 | if not self.parent.root is new: | |
273 | raise ComponentError("Error in setting the root attribute: " |
|
279 | raise ComponentError("Error in setting the root attribute: " | |
274 | "root != parent.root") |
|
280 | "root != parent.root") | |
275 |
|
281 | |||
276 | def _config_changed(self, name, old, new): |
|
282 | def _config_changed(self, name, old, new): | |
277 | """Update all the class traits having ``config=True`` as metadata. |
|
283 | """Update all the class traits having ``config=True`` as metadata. | |
278 |
|
284 | |||
279 | For any class traitlet with a ``config`` metadata attribute that is |
|
285 | For any class traitlet with a ``config`` metadata attribute that is | |
280 | ``True``, we update the traitlet with the value of the corresponding |
|
286 | ``True``, we update the traitlet with the value of the corresponding | |
281 | config entry. |
|
287 | config entry. | |
282 | """ |
|
288 | """ | |
283 | # Get all traitlets with a config metadata entry that is True |
|
289 | # Get all traitlets with a config metadata entry that is True | |
284 | traitlets = self.traitlets(config=True) |
|
290 | traitlets = self.traitlets(config=True) | |
285 |
|
291 | |||
286 | # We auto-load config section for this class as well as any parent |
|
292 | # We auto-load config section for this class as well as any parent | |
287 | # classes that are Component subclasses. This starts with Component |
|
293 | # classes that are Component subclasses. This starts with Component | |
288 | # and works down the mro loading the config for each section. |
|
294 | # and works down the mro loading the config for each section. | |
289 | section_names = [cls.__name__ for cls in \ |
|
295 | section_names = [cls.__name__ for cls in \ | |
290 | reversed(self.__class__.__mro__) if |
|
296 | reversed(self.__class__.__mro__) if | |
291 | issubclass(cls, Component) and issubclass(self.__class__, cls)] |
|
297 | issubclass(cls, Component) and issubclass(self.__class__, cls)] | |
292 |
|
298 | |||
293 | for sname in section_names: |
|
299 | for sname in section_names: | |
294 | # Don't do a blind getattr as that would cause the config to |
|
300 | # Don't do a blind getattr as that would cause the config to | |
295 | # dynamically create the section with name self.__class__.__name__. |
|
301 | # dynamically create the section with name self.__class__.__name__. | |
296 | if new._has_section(sname): |
|
302 | if new._has_section(sname): | |
297 | my_config = new[sname] |
|
303 | my_config = new[sname] | |
298 | for k, v in traitlets.items(): |
|
304 | for k, v in traitlets.items(): | |
299 | # Don't allow traitlets with config=True to start with |
|
305 | # Don't allow traitlets with config=True to start with | |
300 | # uppercase. Otherwise, they are confused with Config |
|
306 | # uppercase. Otherwise, they are confused with Config | |
301 | # subsections. But, developers shouldn't have uppercase |
|
307 | # subsections. But, developers shouldn't have uppercase | |
302 | # attributes anyways! (PEP 6) |
|
308 | # attributes anyways! (PEP 6) | |
303 | if k[0].upper()==k[0] and not k.startswith('_'): |
|
309 | if k[0].upper()==k[0] and not k.startswith('_'): | |
304 | raise ComponentError('Component traitlets with ' |
|
310 | raise ComponentError('Component traitlets with ' | |
305 | 'config=True must start with a lowercase so they are ' |
|
311 | 'config=True must start with a lowercase so they are ' | |
306 | 'not confused with Config subsections: %s.%s' % \ |
|
312 | 'not confused with Config subsections: %s.%s' % \ | |
307 | (self.__class__.__name__, k)) |
|
313 | (self.__class__.__name__, k)) | |
308 | try: |
|
314 | try: | |
309 | # Here we grab the value from the config |
|
315 | # Here we grab the value from the config | |
310 | # If k has the naming convention of a config |
|
316 | # If k has the naming convention of a config | |
311 | # section, it will be auto created. |
|
317 | # section, it will be auto created. | |
312 | config_value = my_config[k] |
|
318 | config_value = my_config[k] | |
313 | except KeyError: |
|
319 | except KeyError: | |
314 | pass |
|
320 | pass | |
315 | else: |
|
321 | else: | |
316 | # print "Setting %s.%s from %s.%s=%r" % \ |
|
322 | # print "Setting %s.%s from %s.%s=%r" % \ | |
317 | # (self.__class__.__name__,k,sname,k,config_value) |
|
323 | # (self.__class__.__name__,k,sname,k,config_value) | |
318 | setattr(self, k, config_value) |
|
324 | # We have to do a deepcopy here if we don't deepcopy the entire | |
|
325 | # config object. If we don't, a mutable config_value will be | |||
|
326 | # shared by all instances, effectively making it a class attribute. | |||
|
327 | setattr(self, k, deepcopy(config_value)) | |||
319 |
|
328 | |||
320 | @property |
|
329 | @property | |
321 | def children(self): |
|
330 | def children(self): | |
322 | """A list of all my child components.""" |
|
331 | """A list of all my child components.""" | |
323 | return self._children |
|
332 | return self._children | |
324 |
|
333 | |||
325 | def _remove_child(self, child): |
|
334 | def _remove_child(self, child): | |
326 | """A private method for removing children components.""" |
|
335 | """A private method for removing children components.""" | |
327 | if child in self._children: |
|
336 | if child in self._children: | |
328 | index = self._children.index(child) |
|
337 | index = self._children.index(child) | |
329 | del self._children[index] |
|
338 | del self._children[index] | |
330 |
|
339 | |||
331 | def _add_child(self, child): |
|
340 | def _add_child(self, child): | |
332 | """A private method for adding children components.""" |
|
341 | """A private method for adding children components.""" | |
333 | if child not in self._children: |
|
342 | if child not in self._children: | |
334 | self._children.append(child) |
|
343 | self._children.append(child) | |
335 |
|
344 | |||
336 | def __repr__(self): |
|
345 | def __repr__(self): | |
337 | return "<%s('%s')>" % (self.__class__.__name__, self.name) |
|
346 | return "<%s('%s')>" % (self.__class__.__name__, self.name) |
@@ -1,66 +1,66 b'' | |||||
1 | """Count the frequencies of words in a string""" |
|
1 | """Count the frequencies of words in a string""" | |
2 |
|
2 | |||
3 | from __future__ import division |
|
3 | from __future__ import division | |
4 |
|
4 | |||
5 | import cmath as math |
|
5 | import cmath as math | |
6 |
|
6 | |||
7 |
|
7 | |||
8 | def wordfreq(text): |
|
8 | def wordfreq(text): | |
9 | """Return a dictionary of words and word counts in a string.""" |
|
9 | """Return a dictionary of words and word counts in a string.""" | |
10 |
|
10 | |||
11 | freqs = {} |
|
11 | freqs = {} | |
12 | for word in text.split(): |
|
12 | for word in text.split(): | |
13 | lword = word.lower() |
|
13 | lword = word.lower() | |
14 | freqs[lword] = freqs.get(lword, 0) + 1 |
|
14 | freqs[lword] = freqs.get(lword, 0) + 1 | |
15 | return freqs |
|
15 | return freqs | |
16 |
|
16 | |||
17 |
|
17 | |||
18 | def print_wordfreq(freqs, n=10): |
|
18 | def print_wordfreq(freqs, n=10): | |
19 | """Print the n most common words and counts in the freqs dict.""" |
|
19 | """Print the n most common words and counts in the freqs dict.""" | |
20 |
|
20 | |||
21 | words, counts = freqs.keys(), freqs.values() |
|
21 | words, counts = freqs.keys(), freqs.values() | |
22 | items = zip(counts, words) |
|
22 | items = zip(counts, words) | |
23 | items.sort(reverse=True) |
|
23 | items.sort(reverse=True) | |
24 | for (count, word) in items[:n]: |
|
24 | for (count, word) in items[:n]: | |
25 | print word, count |
|
25 | print word, count | |
26 |
|
26 | |||
27 |
|
27 | |||
28 |
def wordfreq_to_weightsize(worddict, minsize= |
|
28 | def wordfreq_to_weightsize(worddict, minsize=25, maxsize=50, minalpha=0.5, maxalpha=1.0): | |
29 | mincount = min(worddict.itervalues()) |
|
29 | mincount = min(worddict.itervalues()) | |
30 | maxcount = max(worddict.itervalues()) |
|
30 | maxcount = max(worddict.itervalues()) | |
31 | weights = {} |
|
31 | weights = {} | |
32 | for k, v in worddict.iteritems(): |
|
32 | for k, v in worddict.iteritems(): | |
33 | w = (v-mincount)/(maxcount-mincount) |
|
33 | w = (v-mincount)/(maxcount-mincount) | |
34 | alpha = minalpha + (maxalpha-minalpha)*w |
|
34 | alpha = minalpha + (maxalpha-minalpha)*w | |
35 | size = minsize + (maxsize-minsize)*w |
|
35 | size = minsize + (maxsize-minsize)*w | |
36 | weights[k] = (alpha, size) |
|
36 | weights[k] = (alpha, size) | |
37 | return weights |
|
37 | return weights | |
38 |
|
38 | |||
39 |
|
39 | |||
40 |
def tagcloud(worddict, n=10, minsize= |
|
40 | def tagcloud(worddict, n=10, minsize=25, maxsize=50, minalpha=0.5, maxalpha=1.0): | |
41 | from matplotlib import pyplot as plt |
|
41 | from matplotlib import pyplot as plt | |
42 | import random |
|
42 | import random | |
43 |
|
43 | |||
44 | worddict = wordfreq_to_weightsize(worddict, minsize, maxsize, minalpha, maxalpha) |
|
44 | worddict = wordfreq_to_weightsize(worddict, minsize, maxsize, minalpha, maxalpha) | |
45 |
|
45 | |||
46 | fig = plt.figure() |
|
46 | fig = plt.figure() | |
47 | ax = fig.add_subplot(111) |
|
47 | ax = fig.add_subplot(111) | |
48 | ax.set_position([0.0,0.0,1.0,1.0]) |
|
48 | ax.set_position([0.0,0.0,1.0,1.0]) | |
49 | plt.xticks([]) |
|
49 | plt.xticks([]) | |
50 | plt.yticks([]) |
|
50 | plt.yticks([]) | |
51 |
|
51 | |||
52 | words = worddict.keys() |
|
52 | words = worddict.keys() | |
53 | alphas = [v[0] for v in worddict.values()] |
|
53 | alphas = [v[0] for v in worddict.values()] | |
54 | sizes = [v[1] for v in worddict.values()] |
|
54 | sizes = [v[1] for v in worddict.values()] | |
55 | items = zip(alphas, sizes, words) |
|
55 | items = zip(alphas, sizes, words) | |
56 | items.sort(reverse=True) |
|
56 | items.sort(reverse=True) | |
57 | for alpha, size, word in items[:n]: |
|
57 | for alpha, size, word in items[:n]: | |
58 | xpos = random.normalvariate(0.5, 0.3) |
|
58 | # xpos = random.normalvariate(0.5, 0.3) | |
59 | ypos = random.normalvariate(0.5, 0.3) |
|
59 | # ypos = random.normalvariate(0.5, 0.3) | |
60 |
|
|
60 | xpos = random.uniform(0.0,1.0) | |
61 |
|
|
61 | ypos = random.uniform(0.0,1.0) | |
62 | ax.text(xpos, ypos, word.lower(), alpha=alpha, fontsize=size) |
|
62 | ax.text(xpos, ypos, word.lower(), alpha=alpha, fontsize=size) | |
63 | ax.autoscale_view() |
|
63 | ax.autoscale_view() | |
64 | return ax |
|
64 | return ax | |
65 |
|
65 | |||
66 | No newline at end of file |
|
66 |
General Comments 0
You need to be logged in to leave comments.
Login now