[Subversion] / PEAK / src / peak / binding / components.py  

Diff of /PEAK/src/peak/binding/components.py

Parent Directory | Revision Log

version 469, Sat Jul 13 21:02:40 2002 UTC version 880, Mon Feb 17 14:19:28 2003 UTC
Line 1 
Line 1 
 """Basic binding tools"""  """Basic binding tools"""
   
 from once import Once, New, WeakBinding  from __future__ import generators
 import meta, modules  from peak.api import *
   
 from weakref import ref, WeakValueDictionary  from once import *
   from interfaces import *
 from peak.naming.names import toName, Syntax, CompoundName  from weakref import WeakValueDictionary
 from peak.naming.interfaces import NameNotFoundException  from types import ModuleType
 from peak.util.EigenData import EigenRegistry  
   from peak.naming.names import toName, AbstractName, COMPOUND_KIND
 from Interface import Interface  from peak.naming.syntax import PathSyntax
 from peak.api import config, NOT_FOUND  from peak.util.EigenData import EigenRegistry, EigenCell
   from peak.config.interfaces import IConfigKey, IPropertyMap
   from peak.util.imports import importString
   
   
 __all__ = [  __all__ = [
     'Component','AutoCreated','Provider','CachingProvider',      'Base', 'Component',
     'bindTo', 'requireBinding', 'bindToNames', 'bindToParent', 'bindToSelf',      'bindTo', 'requireBinding', 'bindSequence', 'bindToParent', 'bindToSelf',
     'getRootComponent', 'getParentComponent', 'lookupComponent',      'getRootComponent', 'getParentComponent', 'lookupComponent',
     'acquireComponent', 'globalLookup'      'acquireComponent', 'globalLookup',
       'bindToUtilities', 'bindToProperty', 'Constant',
       'getComponentName', 'getComponentPath', 'Acquire', 'ComponentName',
 ]  ]
   
   
 InterfaceClass = Interface.__class__  
   
   
   
Line 36 
Line 39 
   
   
   
   def getComponentPath(component, relativeTo=None):
   
       """Get 'ComponentName' that would traverse from 'relativeTo' to 'component'
   
       If 'relativeTo' is 'None' or not supplied, the path returned is relative
       to the root component of 'component'.  Note that if supplied, 'relativeTo'
       must be an ancestor (parent, parent's parent, etc.) of 'component'."""
   
 def Provider(callable):      path = []; root=None
     return lambda foundIn, forObj: callable(forObj)  
   
       if relativeTo is None:
           root = getRootComponent(component)
   
 def CachingProvider(callable, weak=False):      c = component
   
     def provider(foundIn, forObj):      while 1:
   
         fid = id(foundIn)          if c is root:
         utility = provider.cache.get(fid)              path.append(''); break
   
         if utility is None:          elif c is relativeTo:
             utility = provider.cache[fid] = callable(foundIn)              break
   
         return utility          path.append(getComponentName(c) or '*')
   
     if weak:          c = getParentComponent(c)
         provider.cache = WeakValueDictionary()  
     else:  
         provider.cache = {}  
   
     return provider          if c is None:
               break
   
       path.reverse()
       return ComponentName(path)
   
   
   
Line 71 
Line 80 
   
   
   
   def Constant(provides, value, doc=None):
       """Supply a constant as a property or utility"""
       return Once(lambda s,d,a: value, provides=provides, doc=doc)
   
   
   def getParentComponent(component):
   
       """Return parent of 'component', or 'None' if root or non-component"""
   
       try:
           gpc = component.__class__.getParentComponent
   
       except AttributeError:
   
           if isinstance(component,ModuleType):
               m = '.'.join(component.__name__.split('.')[:-1])
               if m: return importString(m)
   
       else:
           return gpc(component)
   
   
 def getParentComponent(component):  def getComponentName(component):
   
     """Return parent of 'component', or 'None' if root or non-component"""      """Return name of 'component', or 'None' if root or non-component"""
   
     try:      try:
         gpc = component.getParentComponent          gcn = component.__class__.getComponentName
   
     except AttributeError:      except AttributeError:
         pass  
           if isinstance(component,ModuleType):
               return component.__name__.split('.')[-1]
   
     else:      else:
         return gpc()          return gcn(component)
   
   
   
   
   
 def getRootComponent(component):  def getRootComponent(component):
Line 105 
Line 134 
     return component      return component
   
   
 def globalLookup(name, component=None):  def globalLookup(name, component=None, targetName=None):
   
     """Lookup 'name' in global 'InitialContext', w/'component' in environ"""  
   
     from peak.naming.api import InitialContext  
   
     return InitialContext(RELATIVE_TO_COMPONENT=component).lookup(name)  
   
   
   
   
   
   
       """Lookup 'name' in global 'InitialContext', relative to 'component'"""
   
       return naming.lookup(name, component,
           creationParent=component, creationName=targetName
       )
   
   
 def acquireComponent(component, name):  def acquireComponent(name, component=None, targetName=None):
   
     """Acquire 'name' relative to 'component', w/fallback to globalLookup()"""      """Acquire 'name' relative to 'component', w/fallback to globalLookup()"""
   
Line 137 
Line 159 
         target = getParentComponent(target)          target = getParentComponent(target)
   
     else:      else:
         return globalLookup(name, component)          return globalLookup(name, component, targetName)
   
   
   
   class ComponentName(AbstractName):
   
       """Path between components
   
       Component Path Syntax
   
           Paths are '"/"' separated attribute names.  Path segments of '"."' and
           '".."' mean the same as they do in URLs.  A leading '"/"' (or a
           compound name beginning with an empty path segment), will be treated
           as an "absolute path" relative to the component's root component.
   
           Paths beginning with anything other than '"/"', '"./"', or '"../"' are
           acquired, which means that the first path segment will be looked
           up using 'acquireComponent()' before processing the rest of the path.
           (See 'acquireComponent()' for more details.)  If you do not want
           a name to be acquired, simply prefix it with './' so it is relative
           to the starting object.
   
           All path segments after the first are interpreted as attribute names
           to be looked up, beginning at the component referenced by the first
           path segment.  '.' and '..' are interpreted the same as for the first
           path segment.
       """
   
       nameKind = COMPOUND_KIND
   
       syntax = PathSyntax(
           direction = 1,
           separator = '/',
       )
   
   
   
Line 159 
Line 203 
   
   
   
   def lookupComponent(name, component=None):
   
       """Lookup 'name' relative to 'component'
   
       'name' can be any name acceptable to the 'peak.naming' package, or an
       Interface object.  Strings and compound names will be interpreted
       as paths relative to the starting component.  An empty name will return
       the starting component.  Interfaces and Properties will be looked up using
       'config.findUtility(name, component)'.  All other kinds of names,
       including URL strings and 'CompositeName' instances, will be looked up
       using 'binding.globalLookup()'.
   
 ComponentNameSyntax = Syntax(      Regardless of how the lookup is processed, an 'exceptions.NameNotFound'
     direction = 1,      error will be raised if the name cannot be found."""
     separator = '/',  
 )  
   
       return _lookupComponent(component, name)
   
 def ComponentName(nameStr):  
     return CompoundName(nameStr, ComponentNameSyntax)  
   
   
 _getFirstPathComponent = dict( (  _getFirstPathComponent = dict( (
Line 194 
Line 244 
   
   
   
   def _lookupComponent(component, name, targetName=None):
   
       if IConfigKey.isImplementedBy(name):
           return config.findUtility(name, component)
   
   
   
   
   
   
 def lookupComponent(component, name):  
   
     """Lookup 'name' relative to 'component'  
   
     'name' can be any name acceptable to the 'peak.naming' package, or an  
     Interface object.  Strings and 'CompoundName' names will be interpreted  
     as paths relative to the starting component.  An empty name will return  
     the starting component.  Interfaces will be lookedup using  
     'component.acquireUtility()'.  All other kinds of names, including URL  
     strings and 'CompositeName' instances, will be looked up using  
     'binding.globalLookup()'.  
   
     Regardless of how the lookup is processed, a 'naming.NameNotFoundException'  
     will be raised if the name cannot be found.  
   
     Component Path Syntax  
   
         Paths are '/'-separated attribute names.  Path segments of '.' and  
         '..' mean the same as they do in URLs.  A leading '/' (or a  
         CompoundName beginning with an empty path segment), will be treated  
         as an "absolute path" relative to the component's root component.  
   
         Paths beginning with anything other than '/', './', or '../' are  
         acquired, which means that the first path segment will be looked  
         up using 'acquireComponent()' before processing the rest of the path.  
         (See 'acquireComponent()' for more details.)  If you do not want  
         a name to be acquired, simply prefix it with './' so it is relative  
         to the starting object.  
   
         All path segments after the first are interpreted as attribute names  
         to be looked up, beginning at the component referenced by the first  
         path segment.  '.' and '..' are interpreted the same as for the first  
         path segment."""  
   
     if isinstance(name, InterfaceClass):  
         utility = component.acquireUtility(name)  
         if utility is None:  
             raise NameNotFoundException(name, resolvedObj = component)  
   
     parsedName = toName(name, ComponentName, 1)      parsedName = toName(name, ComponentName, 1)
   
       if not parsedName.nameKind == COMPOUND_KIND:
     # URL's and composite names must be handled globally      # URL's and composite names must be handled globally
           return globalLookup(name, component, targetName)
   
     if not parsedName.isCompound:      if not parsedName:  # empty name refers to self
         return globalLookup(name, component)  
   
     if not parsedName:  
         # empty name refers to self  
         return component          return component
   
     parts = iter(parsedName)      parts = iter(parsedName)
   
     attr = parts.next() # first part      attr = parts.next() # first part
     pc = _getFirstPathComponent(attr)      pc = _getFirstPathComponent(attr)
   
     if pc:      if pc:  ob = pc(component)
         ob = pc(component)      else:   ob = acquireComponent(attr, component, targetName)
     else:  
         ob = acquireComponent(component,attr)  
   
     resolved = []      resolved = []
     append = resolved.append      append = resolved.append
Line 269 
Line 271 
     try:      try:
         for attr in parts:          for attr in parts:
             pc = _getNextPathComponent(attr)              pc = _getNextPathComponent(attr)
             if pc:              if pc:  ob = pc(ob)
                 ob = pc(ob)              else:   ob = getattr(ob,attr)
             else:  
                 ob = getattr(ob,attr)  
             append(attr)              append(attr)
   
     except AttributeError:      except AttributeError:
   
         raise NameNotFoundException(          raise exceptions.NameNotFound(
             resolvedName = ComponentName(resolved),              resolvedName = ComponentName(resolved),
             remainingName = ComponentName([attr] + [a for a in parts]),              remainingName = ComponentName([attr] + [a for a in parts]),
             resolvedObj = ob              resolvedObj = ob
Line 295 
Line 295 
   
                 thingINeed = binding.bindTo("path/to/service")                  thingINeed = binding.bindTo("path/to/service")
   
                 getOtherThing = binding.bindTo("some/thing", weak=True)  
   
         'someClass' can then refer to 'self.thingINeed' instead of          'someClass' can then refer to 'self.thingINeed' instead of
         calling 'self.lookupComponent("path/to/service")' repeatedly.          calling 'self.lookupComponent("path/to/service")' repeatedly.
         It can also do 'self.getOtherThing()' to get '"some/thing"'.  
         (The 'weak' argument, if true, means to bind to a weak reference.)  
     """      """
   
     singleValue = True      singleValue = True
   
     def __init__(self,targetName,weak=False,provides=None):  
       def __init__(self,targetName,provides=None,doc=None):
   
         self.targetNames = (targetName,)          self.targetNames = (targetName,)
         self.weak = weak  
         self._provides=provides          self._provides=provides
           self.__doc__ = doc or ("binding.bindTo(%r)" % targetName)
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
     def computeValue(self, obj, instanceDict, attrName):      def computeValue(self, obj, instanceDict, attrName):
   
         names = self.targetNames          names = self.targetNames
         obs   = map(obj.lookupComponent, names)          obs   = [_lookupComponent(obj,n,attrName) for n in names]
   
         for name,newOb in zip(names, obs):          for name,newOb in zip(names, obs):
   
             if newOb is NOT_FOUND:              if newOb is NOT_FOUND:
   
                 del instanceDict[attrName]                  del instanceDict[attrName]
                 raise NameNotFoundError(attrName, resolvedName = name)                  raise exceptions.NameNotFound(attrName, resolvedName = name)
   
             if self.singleValue:              if self.singleValue:
   
                 if self.weak:  
                     return ref(newOb)  
                 else:  
                     return newOb                      return newOb
   
         if self.weak:  
             obs = map(ref,obs)  
   
         return tuple(obs)          return tuple(obs)
   
   
   class bindSequence(bindTo):
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
 class bindToNames(bindTo):  
   
     """Automatically look up and cache a sequence of services by name      """Automatically look up and cache a sequence of services by name
   
Line 375 
Line 334 
   
             class someClass(binding.AutoCreated):              class someClass(binding.AutoCreated):
   
                 thingINeed = binding.bindToNames(                  thingINeed = binding.bindSequence(
                     "path/to/service", "another/path", ...                      "path/to/service", "another/path", ...
                 )                  )
   
         'someClass' can then refer to 'self.thingINeed' to get a tuple of          'someClass' can then refer to 'self.thingINeed' to get a tuple of
         services instead of calling 'self.lookupComponent()' on a series of          services instead of calling 'self.lookupComponent()' on a series of
         names.  As with 'bindTo()', a 'weak' keyword argument can be set to          names.
         indicate that the sequence should consist of weak references to the  
         named objects.  
     """      """
   
     singleValue = False      singleValue = False
   
     def __init__(self, *targetNames, **kw):      def __init__(self, *targetNames, **kw):
         self.targetNames = targetNames          self.targetNames = targetNames
         self.weak = kw.get('weak')  
         self._provides = kw.get('provides')          self._provides = kw.get('provides')
           self.__doc__ = kw.get('doc',("binding.bindSequence%s" % `targetNames`))
   
   
   def Acquire(key,doc=None):
   
       if not IConfigKey.isImplementedBy(key):
           raise exceptions.InvalidName("Not a configuration key:", key)
   
       return bindTo(key,key,doc)
   
   
   
Line 406 
Line 367 
   
   
   
   def bindToParent(level=1, name=None, provides=None, doc=None):
   
       """Look up and cache a reference to the nth-level parent component
 class bindToParent(WeakBinding):  
   
     """Look up and cache a weak ref to the nth-level parent component  
   
         Usage::          Usage::
   
Line 422 
Line 381 
        'self.getParentComponent().getParentComponent()'.         'self.getParentComponent().getParentComponent()'.
     """      """
   
     def __init__(self,level=1,provides=None):      def computeValue(obj, instDict, attrName):
         self.level = level  
         self._provides = provides  
   
     def computeValue(self, obj, instDict, attrName):          for step in range(level):
               newObj = getParentComponent(obj)
         for step in range(self.level):  
             newObj = obj.getParentComponent()  
             if newObj is None: break              if newObj is None: break
             obj = newObj              obj = newObj
   
         return obj          return obj
   
       return Once(computeValue, name=name, provides=provides, doc=doc)
   
   
 def bindToSelf(provides=None):  def bindToSelf(name=None, provides=None, doc=None):
   
     """Weak reference to the 'self' object      """Cached reference to the 'self' object
   
     This is just a shortcut for 'bindToParent(0)', and does pretty much what      This is just a shortcut for 'bindToParent(0)', and does pretty much what
     you'd expect.  It's handy for objects that provide default support for      you'd expect.  It's handy for objects that provide default support for
Line 446 
Line 403 
     can refer to 'self.delegateForInterfaceX.someMethod()', and have      can refer to 'self.delegateForInterfaceX.someMethod()', and have
     'delegateForInterfaceX' be a 'bindToSelf()' by default."""      'delegateForInterfaceX' be a 'bindToSelf()' by default."""
   
     return bindToParent(0,provides)      return bindToParent(0,name,provides,doc)
   
   
   
   
 class requireBinding(Once):  class requireBinding(Once):
   
     """Placeholder for a binding that should be (re)defined by a subclass"""      """Placeholder for a binding that should be (re)defined by a subclass"""
   
     def __init__(self,description="",provides=None):      def __init__(self,description="",name=None,provides=None,doc=None):
         self.description = description          self.description = description
         self._provides = provides          self._provides = provides
           self.__doc__ = doc or ("binding.requireBinding: %s" % description)
           self.attrName = self.__name__ = name
   
     def computeValue(self, obj, instanceDict, attrName):      def computeValue(self, obj, instanceDict, attrName):
   
Line 464 
Line 425 
         )          )
   
   
   def bindToUtilities(iface, provides=None, doc=None):
   
       """Binding to a list of all 'iface' utilities above the component"""
   
       return Once(lambda s,d,a: list(config.findUtilities(iface,s)),
           provides=provides, doc=doc
       )
   
   
   def bindToProperty(propName, default=NOT_GIVEN, provides=None, doc=None):
   
       """Binding to property 'propName', defaulting to 'default' if not found
   
           If 'default' is not supplied, failure to locate the named property
           will result in a 'config.PropertyNotFound' exception.
       """
   
       propName = PropertyName(propName)
   
       return Once(lambda s,d,a: config.getProperty(propName,s,default),
           provides=provides, doc=doc
       )
   
   
   class Base(object):
   
       """Thing that can be composed into a component tree, w/binding & lookups"""
   
       __class_implements__ = IBindingFactory
       __implements__       = IBindingAPI
       __metaclass__        = ActiveClass
   
   
       def __init__(self, parentComponent=None, componentName=None, **kw):
   
           self.setParentComponent(parentComponent,componentName)
   
           if kw:
   
               klass = self.__class__
   
               for k,v in kw.iteritems():
   
                   if hasattr(klass,k):
                       setattr(self,k,v)
   
                   else:
                       raise TypeError(
                           "%s constructor has no keyword argument %s" %
                           (klass, k)
                       )
   
       lookupComponent = _lookupComponent
   
       def setParentComponent(self, parentComponent, componentName=None):
           self.__parentCell.set(parentComponent)
           self.__componentName = componentName
   
       __componentName = None
   
   
   
 class Component(object):  
   
     """Thing that can be composed into a component tree, w/binding & lookups"""  
   
     __metaclasses__  = (  
         meta.AssertInterfaces, meta.ActiveDescriptors  
     )  
   
     # use the global lookupComponent function as a method      def getParentComponent(self):
           return self.__parentCell.get()
   
     lookupComponent = lookupComponent      def getComponentName(self):
           return self.__componentName
   
     def setParentComponent(self,parent):      def __parentCell(s,d,a):
         from weakref import ref          cell = EigenCell()
         self.getParentComponent = ref(parent)          cell.set(None)
           s.getParentComponent = cell.get
           return cell
   
     def getParentComponent(self):      __parentCell = Once(__parentCell)
         return None  
   
     def _componentName(self, dict, name):      def _getConfigData(self, configKey, forObj):
         return self.__class__.__name__.split('.')[-1]          return NOT_FOUND
   
     _componentName = Once(_componentName)  
   
     __instance_provides__ = New(EigenRegistry)      def _hasBinding(self,attr,useSlot=False):
   
           if useSlot:
               return hasattr(self,attr)
           else:
               return attr in self.__dict__
   
   
       def _bindingChanging(self,attr,newval,isSlot=False):
           pass
   
     __class_provides__ = EigenRegistry()  
   
       def _postGet(self,attr,value,isSlot=False):
           return value
   
   
   
Line 527 
Line 531 
   
   
   
       def _setBinding(self, attr, value, useSlot=False):
   
           self._bindingChanging(attr,value,useSlot)
   
           if useSlot:
               getattr(self.__class__,attr).__set__(self,value)
   
           else:
               self.__dict__[attr] = value
   
     def acquireUtility(self, iface, forObj=None, localLookup=True):  
   
         if forObj is None:      def _getBinding(self, attr, default=None, useSlot=False):
             forObj=self  
   
         if localLookup:          if useSlot:
               val = getattr(self,attr,default)
   
             provider = self.__instance_provides__.get(iface)          else:
               val = self.__dict__.get(attr,default)
   
             if provider is not None:          if val is not default:
                 return provider(self,forObj)  
   
             attr = self.__class_provides__.get(iface)              val = self._postGet(attr,val,useSlot)
   
             if attr is not None:              if val is NOT_FOUND:
                   return default
   
                 utility = getattr(self,attr)          return val
   
                 if utility is not NOT_FOUND:  
                     return utility  
   
         parent = self.getParentComponent()  
   
         if parent is None:  
             parent = config.getLocal(self)  
   
         return parent.acquireUtility(iface,forObj)  
   
   
     def registerProvider(self, ifaces, provider):  
         self.__instance_provides__.register(ifaces, provider)  
   
   
   
Line 570 
Line 572 
   
   
   
       def _delBinding(self, attr, useSlot=False):
   
           self._bindingChanging(attr, NOT_FOUND, useSlot)
   
 class AutoCreatable(type):          if useSlot:
               d = getattr(self.__class__,attr).__delete__
   
     """Metaclass for components which auto-create when used"""              try:
                   d(self)
               except AttributeError:
                   pass
   
     def __get__(self, obj, typ=None):          elif attr in self.__dict__:
               del self.__dict__[attr]
   
         if obj is None:  
             return self  
   
         newOb = self(obj)  
   
         obj.__dict__[newOb._componentName] = newOb  
         return newOb  
   
   
 class AutoCreated(Component):  
   
     """Component that auto-creates itself in instances of its containing class  
     """  
   
     __metaclasses__ = AutoCreatable,  
   
     def __init__(self, parent=None):  
   
         super(AutoCreated,self).__init__()  
   
         if parent is not None:  
             self.setParentComponent(parent)  
   
   
   
Line 613 
Line 609 
   
   
   
 modules.setupModule()  
   
   
   
   
   class Component(Base):
   
       """An configurable implementation (i.e., solution-domain) component"""
   
       __implements__ = IComponent
   
       __instance_provides__ = New(
           'peak.config.config_components:PropertyMap', provides=IPropertyMap
       )
   
       __class_provides__    = EigenRegistry()
   
   
       def _getConfigData(self, configKey, forObj):
   
           attr = self._getBinding('__instance_provides__')
   
           if attr:
               value = attr.getValueFor(configKey, forObj)
   
               if value is not NOT_FOUND:
                   return value
   
           attr = self.__class_provides__.get(configKey)
   
           if attr:
               return getattr(self, attr, NOT_FOUND)
   
           return NOT_FOUND
   
   
       def registerProvider(self, configKeys, provider):
           self.__instance_provides__.registerProvider(configKeys, provider)
   
   
   


Generate output suitable for use with a patch program
Legend:
Removed from v.469  
changed lines
  Added in v.880

cvs-admin@eby-sarna.com

Powered by ViewCVS 1.0-dev

ViewCVS and CVS Help