##// END OF EJS Templates
Important changes to simplify traitlets....
Important changes to simplify traitlets. Some aspect of traitlets were a bit too magical for us. Thus, we have simplified certain things to make it more straitforward: * Default values are always validated, but now, this is done when the HasTraitlets.__new__ is called. We used to do this the first time __get__ was called. * The klass argument of Type and Instance traitlets must be a class. Unlike enthought.traits, we are no longer accepting class names as str or instances. * The args and kw arguments to Instance.__init__ are now handled in better manner, but that is quite different from enthought.traits. * More tests of edge cases.

File last commit:

r2181:fd14677a
r2182:4cfda302
Show More
component.py
189 lines | 6.2 KiB | text/x-python | PythonLexer
#!/usr/bin/env python
# encoding: utf-8
"""
A lightweight component system for IPython.
Authors:
* Brian Granger
* Fernando Perez
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2009 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from weakref import WeakValueDictionary
from IPython.utils.ipstruct import Struct
from IPython.utils.traitlets import (
HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
)
#-----------------------------------------------------------------------------
# Helper classes for Components
#-----------------------------------------------------------------------------
class MetaComponentTracker(type):
"""A metaclass that tracks instances of Components and its subclasses."""
def __init__(cls, name, bases, d):
super(MetaComponentTracker, cls).__init__(name, bases, d)
cls.__instance_refs = WeakValueDictionary()
cls.__numcreated = 0
def __call__(cls, *args, **kw):
"""Called when *class* is called (instantiated)!!!
When a Component or subclass is instantiated, this is called and
the instance is saved in a WeakValueDictionary for tracking.
"""
instance = super(MetaComponentTracker, cls).__call__(*args, **kw)
for c in cls.__mro__:
if issubclass(cls, c) and issubclass(c, Component):
c.__numcreated += 1
c.__instance_refs[c.__numcreated] = instance
return instance
def get_instances(cls, name=None, klass=None, root=None):
"""Get all instances of cls and its subclasses.
Parameters
----------
name : str
Limit to components with this name.
klass : class
Limit to components having isinstance(component, klass)
root : Component or subclass
Limit to components having this root.
"""
instances = cls.__instance_refs.values()
if name is not None:
instances = [i for i in instances if i.name == name]
if klass is not None:
instances = [i for i in instances if isinstance(i, klass)]
if root is not None:
instances = [i for i in instances if i.root == root]
return instances
def get_instances_by_condition(cls, call, name=None, klass=None, root=None):
"""Get all instances of cls, i such that call(i)==True.
This also takes the ``name``, ``klass`` and ``root`` arguments of
:meth:`get_instance`
"""
return [i for i in cls.get_instances(name,klass,root) if call(i)]
class ComponentNameGenerator(object):
"""A Singleton to generate unique component names."""
def __init__(self, prefix):
self.prefix = prefix
self.i = 0
def __call__(self):
count = self.i
self.i += 1
return "%s%s" % (self.prefix, count)
ComponentNameGenerator = ComponentNameGenerator('ipython.component')
class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
pass
#-----------------------------------------------------------------------------
# Component implementation
#-----------------------------------------------------------------------------
class Component(HasTraitlets):
__metaclass__ = MetaComponent
# Traitlets are fun!
config = Instance(Struct)
parent = This(allow_none=True)
root = This(allow_none=True)
def __init__(self, parent, name=None, config=None):
"""Create a component given a parent.
Parameters
----------
parent : Component subclass
The parent in the component graph. The parent is used
to get the root of the component graph.
name : str
The unique name of the component. If empty, then a unique
one will be autogenerated.
config : Config
If this is empty, self.config = root.config, otherwise
self.config = config and root.config is ignored. This argument
should be used to pass the config to the root. Otherwise, it
can be used to *override* the inheritance of root.config. If a
caller wants to modify root.config (not override), the caller
should make a copy and change attributes and then pass the copy
to this argument. We might think about changing this behavior.
"""
super(Component, self).__init__()
self._children = []
if name is None:
self.name = ComponentNameGenerator()
else:
self.name = name
self.root = self # This is the default, it is set when parent is set
self.parent = parent
if config is not None:
self.config = config
else:
if self.parent is not None:
self.config = self.parent.config
#-------------------------------------------------------------------------
# Static traitlet notifiations
#-------------------------------------------------------------------------
def _parent_changed(self, name, old, new):
if old is not None:
old._remove_child(self)
if new is not None:
new._add_child(self)
if new is None:
self.root = self
else:
self.root = new.root
@property
def children(self):
"""A list of all my child components."""
return self._children
def _remove_child(self, child):
"""A private method for removing children componenets."""
if child in self._children:
index = self._children.index(child)
del self._children[index]
def _add_child(self, child):
"""A private method for adding children componenets."""
if child not in self._children:
self._children.append(child)
def __repr__(self):
return "<Component('%s')>" % self.name