[Checkins] SVN: zope.component/trunk/ Merge:
Chris McDonough
chrism at plope.com
Thu Sep 15 01:08:23 EST 2011
Log message for revision 122813:
Merge:
svn merge --ignore-ancestry -r122753:122812 svn+ssh://svn.zope.org/repos/main/zope.component/branches/chrism-zope.interface-componentregistry
Changed:
_U zope.component/trunk/
U zope.component/trunk/CHANGES.txt
U zope.component/trunk/buildout.cfg
_U zope.component/trunk/src/
U zope.component/trunk/src/zope/component/globalregistry.py
U zope.component/trunk/src/zope/component/hooks.txt
U zope.component/trunk/src/zope/component/interfaces.py
U zope.component/trunk/src/zope/component/persistentregistry.py
U zope.component/trunk/src/zope/component/registry.py
U zope.component/trunk/src/zope/component/tests.py
-=-
Property changes on: zope.component/trunk
___________________________________________________________________
Modified: svn:ignore
- bin
build
dist
lib
develop-eggs
eggs
parts
.installed.cfg
coverage
+ bin
build
dist
lib
develop-eggs
eggs
parts
.installed.cfg
coverage
.mr.developer.cfg
Modified: zope.component/trunk/CHANGES.txt
===================================================================
--- zope.component/trunk/CHANGES.txt 2011-09-15 05:55:00 UTC (rev 122812)
+++ zope.component/trunk/CHANGES.txt 2011-09-15 06:08:23 UTC (rev 122813)
@@ -4,8 +4,24 @@
3.10.1 (unreleased)
===================
-- Nothing changed yet.
+- Moved code from ``zope.component.registry`` which implements a basic
+ nonperistent component registry to ``zope.interface.registry``. This code
+ was moved from ``zope.component`` into ``zope.interface`` to make porting
+ systems (such as Pyramid) that rely only on a basic component registry to
+ Python 3 possible without needing to port the entirety of the
+ ``zope.component`` package. Backwards compatibility import shims have been
+ left behind in ``zope.component``, so this change will not break any
+ existing code.
+- Interfaces moved from ``zope.component.interfaces`` to
+ ``zope.interface.interfaces``: ``ComponentLookupError``, ``Invalid``,
+ ``IObjectEvent``, ``ObjectEvent``, ``IComponentLookup``, ``IRegistration``,
+ ``IUtilityRegistration``, ``IAdapterRegistration``,
+ ``ISubscriptionAdapterRegistration``, ``IHandlerRegistration``,
+ ``IRegistrationEvent``, ``RegistrationEvent``, ``IRegistered``,
+ ``Registered``, ``IUnregistered``, ``Unregistered``,
+ ``IComponentRegistry``, and ``IComponents``. Backwards compatibility shims
+ left in place.
3.10.0 (2010-09-25)
===================
Modified: zope.component/trunk/buildout.cfg
===================================================================
--- zope.component/trunk/buildout.cfg 2011-09-15 05:55:00 UTC (rev 122812)
+++ zope.component/trunk/buildout.cfg 2011-09-15 06:08:23 UTC (rev 122813)
@@ -2,7 +2,12 @@
develop = .
parts = test test_c_hookable python sphinx coverage-test coverage-report
unzip = true
+extensions = mr.developer
+auto-checkout = zope.interface
+[sources]
+zope.interface = svn svn+ssh://svn.zope.org/repos/main/zope.interface/trunk
+
[test]
recipe = zc.recipe.testrunner
eggs = zope.component [test,zcml,security,persistentregistry]
Property changes on: zope.component/trunk/src
___________________________________________________________________
Modified: svn:ignore
- zope.component.egg-info
+ zope.component.egg-info
zope.interface
Added: svn:externals
+
Modified: zope.component/trunk/src/zope/component/globalregistry.py
===================================================================
--- zope.component/trunk/src/zope/component/globalregistry.py 2011-09-15 05:55:00 UTC (rev 122812)
+++ zope.component/trunk/src/zope/component/globalregistry.py 2011-09-15 06:08:23 UTC (rev 122813)
@@ -15,9 +15,8 @@
"""
from zope.interface import implements
from zope.interface.adapter import AdapterRegistry
-from zope.component.registry import Components
-from zope.component.interfaces import Invalid, IComponentLookup, IRegistry
-from zope.component.interfaces import ComponentLookupError
+from zope.interface.registry import Components
+from zope.component.interfaces import IComponentLookup
def GAR(components, registryName):
return getattr(components, registryName)
@@ -37,6 +36,7 @@
return GAR, (self.__parent__, self.__name__)
class BaseGlobalComponents(Components):
+ implements(IComponentLookup)
def _init_registries(self):
self.adapters = GlobalAdapterRegistry(self, 'adapters')
@@ -67,7 +67,6 @@
def provideUtility(component, provides=None, name=u''):
base.registerUtility(component, provides, name, event=False)
-
def provideAdapter(factory, adapts=None, provides=None, name=''):
base.registerAdapter(factory, adapts, provides, name, event=False)
Modified: zope.component/trunk/src/zope/component/hooks.txt
===================================================================
--- zope.component/trunk/src/zope/component/hooks.txt 2011-09-15 05:55:00 UTC (rev 122812)
+++ zope.component/trunk/src/zope/component/hooks.txt 2011-09-15 06:08:23 UTC (rev 122813)
@@ -26,7 +26,7 @@
``getSiteManager`` method, which is specified by
``zope.component.interfaces.IPossibleSite``:
->>> from zope.component.registry import Components
+>>> from zope.interface.registry import Components
>>> class Site(object):
... def __init__(self):
... self.registry = Components('components')
Modified: zope.component/trunk/src/zope/component/interfaces.py
===================================================================
--- zope.component/trunk/src/zope/component/interfaces.py 2011-09-15 05:55:00 UTC (rev 122812)
+++ zope.component/trunk/src/zope/component/interfaces.py 2011-09-15 06:08:23 UTC (rev 122813)
@@ -13,38 +13,31 @@
############################################################################
"""Component and Component Architecture Interfaces
"""
-__docformat__ = "reStructuredText"
-
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import implements
-class ComponentLookupError(LookupError):
- """A component could not be found."""
+# BBB 2011-09-09, import interfaces from zope.interface
+from zope.interface.interfaces import ComponentLookupError
+from zope.interface.interfaces import Invalid
+from zope.interface.interfaces import IObjectEvent
+from zope.interface.interfaces import ObjectEvent
+from zope.interface.interfaces import IComponentLookup
+from zope.interface.interfaces import IRegistration
+from zope.interface.interfaces import IUtilityRegistration
+from zope.interface.interfaces import _IBaseAdapterRegistration
+from zope.interface.interfaces import IAdapterRegistration
+from zope.interface.interfaces import ISubscriptionAdapterRegistration
+from zope.interface.interfaces import IHandlerRegistration
+from zope.interface.interfaces import IRegistrationEvent
+from zope.interface.interfaces import RegistrationEvent
+from zope.interface.interfaces import IRegistered
+from zope.interface.interfaces import Registered
+from zope.interface.interfaces import IUnregistered
+from zope.interface.interfaces import Unregistered
+from zope.interface.interfaces import IComponentRegistry
+from zope.interface.interfaces import IComponents
-class Invalid(Exception):
- """A component doesn't satisfy a promise."""
-
-class Misused(Exception):
- """A component is being used (registered) for the wrong interface."""
-
-
-class IObjectEvent(Interface):
- """An event related to an object.
-
- The object that generated this event is not necessarily the object
- refered to by location.
- """
-
- object = Attribute("The subject of the event.")
-
-
-class ObjectEvent(object):
- implements(IObjectEvent)
-
- def __init__(self, object):
- self.object = object
-
class IComponentArchitecture(Interface):
"""The Component Architecture is defined by two key components: Adapters
and Utiltities. Both are managed by site managers. All other components
@@ -305,87 +298,15 @@
create objects which implement the given interface.
"""
-class IComponentLookup(Interface):
- """Component Manager for a Site
- This object manages the components registered at a particular site. The
- definition of a site is intentionally vague.
+class IRegistry(Interface):
+ """Object that supports component registry
"""
- adapters = Attribute(
- "Adapter Registry to manage all registered adapters.")
-
- utilities = Attribute(
- "Adapter Registry to manage all registered utilities.")
-
- def queryAdapter(object, interface, name=u'', default=None):
- """Look for a named adapter to an interface for an object
-
- If a matching adapter cannot be found, returns the default.
+ def registrations():
+ """Return an iterable of component registrations
"""
- def getAdapter(object, interface, name=u''):
- """Look for a named adapter to an interface for an object
-
- If a matching adapter cannot be found, a ComponentLookupError
- is raised.
- """
-
- def queryMultiAdapter(objects, interface, name=u'', default=None):
- """Look for a multi-adapter to an interface for multiple objects
-
- If a matching adapter cannot be found, returns the default.
- """
-
- def getMultiAdapter(objects, interface, name=u''):
- """Look for a multi-adapter to an interface for multiple objects
-
- If a matching adapter cannot be found, a ComponentLookupError
- is raised.
- """
-
- def getAdapters(objects, provided):
- """Look for all matching adapters to a provided interface for objects
-
- Return an iterable of name-adapter pairs for adapters that
- provide the given interface.
- """
-
- def subscribers(objects, provided):
- """Get subscribers
-
- Subscribers are returned that provide the provided interface
- and that depend on and are comuted from the sequence of
- required objects.
- """
-
- def handle(*objects):
- """Call handlers for the given objects
-
- Handlers registered for the given objects are called.
- """
-
- def queryUtility(interface, name='', default=None):
- """Look up a utility that provides an interface.
-
- If one is not found, returns default.
- """
-
- def getUtilitiesFor(interface):
- """Look up the registered utilities that provide an interface.
-
- Returns an iterable of name-utility pairs.
- """
-
- def getAllUtilitiesRegisteredFor(interface):
- """Return all registered utilities for an interface
-
- This includes overridden utilities.
-
- An iterable of utility instances is returned. No names are
- returned.
- """
-
class IComponentRegistrationConvenience(Interface):
"""API for registering components.
@@ -468,14 +389,28 @@
activity.
"""
-class IRegistry(Interface):
- """Object that supports component registry
+
+class IPossibleSite(Interface):
+ """An object that could be a site.
"""
- def registrations():
- """Return an iterable of component registrations
+ def setSiteManager(sitemanager):
+ """Sets the site manager for this object.
"""
+ def getSiteManager():
+ """Returns the site manager contained in this object.
+
+ If there isn't a site manager, raise a component lookup.
+ """
+
+class ISite(IPossibleSite):
+ """Marker interface to indicate that we have a site"""
+
+class Misused(Exception):
+ """A component is being used (registered) for the wrong interface."""
+
+
class IFactory(Interface):
"""A factory is responsible for creating other components."""
@@ -495,448 +430,3 @@
instance cannot be created, an empty Implements instance is returned.
"""
-class IRegistration(Interface):
- """A registration-information object
- """
-
- registry = Attribute("The registry having the registration")
-
- name = Attribute("The registration name")
-
- info = Attribute("""Information about the registration
-
- This is information deemed useful to people browsing the
- configuration of a system. It could, for example, include
- commentary or information about the source of the configuration.
- """)
-
-class IUtilityRegistration(IRegistration):
- """Information about the registration of a utility
- """
-
- factory = Attribute("The factory used to create the utility. Optional.")
- component = Attribute("The object registered")
- provided = Attribute("The interface provided by the component")
-
-class _IBaseAdapterRegistration(IRegistration):
- """Information about the registration of an adapter
- """
-
- factory = Attribute("The factory used to create adapters")
-
- required = Attribute("""The adapted interfaces
-
- This is a sequence of interfaces adapters by the registered
- factory. The factory will be caled with a sequence of objects, as
- positional arguments, that provide these interfaces.
- """)
-
- provided = Attribute("""The interface provided by the adapters.
-
- This interface is implemented by the factory
- """)
-
-class IAdapterRegistration(_IBaseAdapterRegistration):
- """Information about the registration of an adapter
- """
-
-class ISubscriptionAdapterRegistration(_IBaseAdapterRegistration):
- """Information about the registration of a subscription adapter
- """
-
-class IHandlerRegistration(IRegistration):
-
- handler = Attribute("An object called used to handle an event")
-
- required = Attribute("""The handled interfaces
-
- This is a sequence of interfaces handled by the registered
- handler. The handler will be caled with a sequence of objects, as
- positional arguments, that provide these interfaces.
- """)
-
-class IRegistrationEvent(IObjectEvent):
- """An event that involves a registration"""
-
-class RegistrationEvent(ObjectEvent):
- """There has been a change in a registration
- """
- implements(IRegistrationEvent)
-
- def __repr__(self):
- return "%s event:\n%r" % (self.__class__.__name__, self.object)
-
-class IRegistered(IRegistrationEvent):
- """A component or factory was registered
- """
-
-class Registered(RegistrationEvent):
- implements(IRegistered)
-
-class IUnregistered(IRegistrationEvent):
- """A component or factory was unregistered
- """
-
-class Unregistered(RegistrationEvent):
- """A component or factory was unregistered
- """
- implements(IUnregistered)
-
-class IComponentRegistry(Interface):
- """Register components
- """
-
- def registerUtility(component=None, provided=None, name=u'', info=u'', factory=None):
- """Register a utility
-
- factory
- Factory for the component to be registerd.
-
- component
- The registered component
-
- provided
- This is the interface provided by the utility. If the
- component provides a single interface, then this
- argument is optional and the component-implemented
- interface will be used.
-
- name
- The utility name.
-
- info
- An object that can be converted to a string to provide
- information about the registration.
-
- Only one of component and factory can be used.
- A Registered event is generated with an IUtilityRegistration.
- """
-
- def unregisterUtility(component=None, provided=None, name=u'', factory=None):
- """Unregister a utility
-
- A boolean is returned indicating whether the registry was
- changed. If the given component is None and there is no
- component registered, or if the given component is not
- None and is not registered, then the function returns
- False, otherwise it returns True.
-
- factory
- Factory for the component to be unregisterd.
-
- component
- The registered component The given component can be
- None, in which case any component registered to provide
- the given provided interface with the given name is
- unregistered.
-
- provided
- This is the interface provided by the utility. If the
- component is not None and provides a single interface,
- then this argument is optional and the
- component-implemented interface will be used.
-
- name
- The utility name.
-
- Only one of component and factory can be used.
- An UnRegistered event is generated with an IUtilityRegistration.
- """
-
- def registeredUtilities():
- """Return an iterable of IUtilityRegistration instances.
-
- These registrations describe the current utility registrations
- in the object.
- """
-
- def registerAdapter(factory, required=None, provided=None, name=u'',
- info=u''):
- """Register an adapter factory
-
- Parameters:
-
- factory
- The object used to compute the adapter
-
- required
- This is a sequence of specifications for objects to be
- adapted. If omitted, then the value of the factory's
- __component_adapts__ attribute will be used. The
- __component_adapts__ attribute is usually attribute is
- normally set in class definitions using adapts
- function, or for callables using the adapter
- decorator. If the factory doesn't have a
- __component_adapts__ adapts attribute, then this
- argument is required.
-
- provided
- This is the interface provided by the adapter and
- implemented by the factory. If the factory
- implements a single interface, then this argument is
- optional and the factory-implemented interface will be
- used.
-
- name
- The adapter name.
-
- info
- An object that can be converted to a string to provide
- information about the registration.
-
- A Registered event is generated with an IAdapterRegistration.
- """
-
- def unregisterAdapter(factory=None, required=None,
- provided=None, name=u''):
- """Register an adapter factory
-
- A boolean is returned indicating whether the registry was
- changed. If the given component is None and there is no
- component registered, or if the given component is not
- None and is not registered, then the function returns
- False, otherwise it returns True.
-
- Parameters:
-
- factory
- This is the object used to compute the adapter. The
- factory can be None, in which case any factory
- registered to implement the given provided interface
- for the given required specifications with the given
- name is unregistered.
-
- required
- This is a sequence of specifications for objects to be
- adapted. If the factory is not None and the required
- arguments is omitted, then the value of the factory's
- __component_adapts__ attribute will be used. The
- __component_adapts__ attribute attribute is normally
- set in class definitions using adapts function, or for
- callables using the adapter decorator. If the factory
- is None or doesn't have a __component_adapts__ adapts
- attribute, then this argument is required.
-
- provided
- This is the interface provided by the adapter and
- implemented by the factory. If the factory is not
- None and implements a single interface, then this
- argument is optional and the factory-implemented
- interface will be used.
-
- name
- The adapter name.
-
- An Unregistered event is generated with an IAdapterRegistration.
- """
-
- def registeredAdapters():
- """Return an iterable of IAdapterRegistration instances.
-
- These registrations describe the current adapter registrations
- in the object.
- """
-
- def registerSubscriptionAdapter(factory, required=None, provides=None,
- name=u'', info=''):
- """Register a subscriber factory
-
- Parameters:
-
- factory
- The object used to compute the adapter
-
- required
- This is a sequence of specifications for objects to be
- adapted. If omitted, then the value of the factory's
- __component_adapts__ attribute will be used. The
- __component_adapts__ attribute is usually attribute is
- normally set in class definitions using adapts
- function, or for callables using the adapter
- decorator. If the factory doesn't have a
- __component_adapts__ adapts attribute, then this
- argument is required.
-
- provided
- This is the interface provided by the adapter and
- implemented by the factory. If the factory implements
- a single interface, then this argument is optional and
- the factory-implemented interface will be used.
-
- name
- The adapter name.
-
- Currently, only the empty string is accepted. Other
- strings will be accepted in the future when support for
- named subscribers is added.
-
- info
- An object that can be converted to a string to provide
- information about the registration.
-
- A Registered event is generated with an
- ISubscriptionAdapterRegistration.
- """
-
- def unregisterSubscriptionAdapter(factory=None, required=None,
- provides=None, name=u''):
- """Unregister a subscriber factory.
-
- A boolean is returned indicating whether the registry was
- changed. If the given component is None and there is no
- component registered, or if the given component is not
- None and is not registered, then the function returns
- False, otherwise it returns True.
-
- Parameters:
-
- factory
- This is the object used to compute the adapter. The
- factory can be None, in which case any factories
- registered to implement the given provided interface
- for the given required specifications with the given
- name are unregistered.
-
- required
- This is a sequence of specifications for objects to be
- adapted. If the factory is not None and the required
- arguments is omitted, then the value of the factory's
- __component_adapts__ attribute will be used. The
- __component_adapts__ attribute attribute is normally
- set in class definitions using adapts function, or for
- callables using the adapter decorator. If the factory
- is None or doesn't have a __component_adapts__ adapts
- attribute, then this argument is required.
-
- provided
- This is the interface provided by the adapter and
- implemented by the factory. If the factory is not
- None implements a single interface, then this argument
- is optional and the factory-implemented interface will
- be used.
-
- name
- The adapter name.
-
- Currently, only the empty string is accepted. Other
- strings will be accepted in the future when support for
- named subscribers is added.
-
- An Unregistered event is generated with an
- ISubscriptionAdapterRegistration.
- """
-
- def registeredSubscriptionAdapters():
- """Return an iterable of ISubscriptionAdapterRegistration instances.
-
- These registrations describe the current subscription adapter
- registrations in the object.
- """
-
- def registerHandler(handler, required=None, name=u'', info=''):
- """Register a handler.
-
- A handler is a subscriber that doesn't compute an adapter
- but performs some function when called.
-
- Parameters:
-
- handler
- The object used to handle some event represented by
- the objects passed to it.
-
- required
- This is a sequence of specifications for objects to be
- adapted. If omitted, then the value of the factory's
- __component_adapts__ attribute will be used. The
- __component_adapts__ attribute is usually attribute is
- normally set in class definitions using adapts
- function, or for callables using the adapter
- decorator. If the factory doesn't have a
- __component_adapts__ adapts attribute, then this
- argument is required.
-
- name
- The handler name.
-
- Currently, only the empty string is accepted. Other
- strings will be accepted in the future when support for
- named handlers is added.
-
- info
- An object that can be converted to a string to provide
- information about the registration.
-
-
- A Registered event is generated with an IHandlerRegistration.
- """
-
- def unregisterHandler(handler=None, required=None, name=u''):
- """Unregister a handler.
-
- A handler is a subscriber that doesn't compute an adapter
- but performs some function when called.
-
- A boolean is returned indicating whether the registry was
- changed.
-
- Parameters:
-
- handler
- This is the object used to handle some event
- represented by the objects passed to it. The handler
- can be None, in which case any handlers registered for
- the given required specifications with the given are
- unregistered.
-
- required
- This is a sequence of specifications for objects to be
- adapted. If omitted, then the value of the factory's
- __component_adapts__ attribute will be used. The
- __component_adapts__ attribute is usually attribute is
- normally set in class definitions using adapts
- function, or for callables using the adapter
- decorator. If the factory doesn't have a
- __component_adapts__ adapts attribute, then this
- argument is required.
-
- name
- The handler name.
-
- Currently, only the empty string is accepted. Other
- strings will be accepted in the future when support for
- named handlers is added.
-
- An Unregistered event is generated with an IHandlerRegistration.
- """
-
- def registeredHandlers():
- """Return an iterable of IHandlerRegistration instances.
-
- These registrations describe the current handler registrations
- in the object.
- """
-
-
-class IComponents(IComponentLookup, IComponentRegistry):
- """Component registration and access
- """
-
-
-class IPossibleSite(Interface):
- """An object that could be a site.
- """
-
- def setSiteManager(sitemanager):
- """Sets the site manager for this object.
- """
-
- def getSiteManager():
- """Returns the site manager contained in this object.
-
- If there isn't a site manager, raise a component lookup.
- """
-
-
-class ISite(IPossibleSite):
- """Marker interface to indicate that we have a site"""
Modified: zope.component/trunk/src/zope/component/persistentregistry.py
===================================================================
--- zope.component/trunk/src/zope/component/persistentregistry.py 2011-09-15 05:55:00 UTC (rev 122812)
+++ zope.component/trunk/src/zope/component/persistentregistry.py 2011-09-15 06:08:23 UTC (rev 122813)
@@ -17,7 +17,7 @@
import persistent.list
import zope.interface.adapter
-import zope.component.registry
+from zope.interface.registry import Components
class PersistentAdapterRegistry(
zope.interface.adapter.VerifyingAdapterRegistry,
@@ -41,7 +41,7 @@
self._v_lookup.changed(self)
-class PersistentComponents(zope.component.registry.Components):
+class PersistentComponents(Components):
def _init_registries(self):
self.adapters = PersistentAdapterRegistry()
Modified: zope.component/trunk/src/zope/component/registry.py
===================================================================
--- zope.component/trunk/src/zope/component/registry.py 2011-09-15 05:55:00 UTC (rev 122812)
+++ zope.component/trunk/src/zope/component/registry.py 2011-09-15 06:08:23 UTC (rev 122813)
@@ -13,488 +13,25 @@
##############################################################################
"""Basic components support
"""
+# BBB, import component-related from zope.interface
+from zope.interface.registry import Components
+from zope.interface.registry import _getUtilityProvided
+from zope.interface.registry import _getAdapterProvided
+from zope.interface.registry import _getAdapterRequired
+from zope.interface.registry import UtilityRegistration
+from zope.interface.registry import AdapterRegistration
+from zope.interface.registry import SubscriptionRegistration
+from zope.interface.registry import HandlerRegistration
-import types
+from zope.component._api import handle
+from zope.component._declaration import adapter
-from zope.interface import Interface
-from zope.interface import implementedBy
-from zope.interface import implements
-from zope.interface import implementsOnly
-from zope.interface import providedBy
-from zope.interface.adapter import AdapterRegistry
-from zope.interface.interfaces import ISpecification
-
-from zope.component.interfaces import ComponentLookupError
from zope.component.interfaces import IAdapterRegistration
-from zope.component.interfaces import IComponents
from zope.component.interfaces import IHandlerRegistration
from zope.component.interfaces import IRegistrationEvent
from zope.component.interfaces import ISubscriptionAdapterRegistration
from zope.component.interfaces import IUtilityRegistration
-from zope.component.interfaces import Registered
-from zope.component.interfaces import Unregistered
-from zope.component._api import handle
-from zope.component._declaration import adapter
-from zope.event import notify
-class Components(object):
-
- implements(IComponents)
-
- def __init__(self, name='', bases=()):
- assert isinstance(name, basestring)
- self.__name__ = name
- self._init_registries()
- self._init_registrations()
- self.__bases__ = tuple(bases)
-
- def __repr__(self):
- return "<%s %s>" % (self.__class__.__name__, self.__name__)
-
- def _init_registries(self):
- self.adapters = AdapterRegistry()
- self.utilities = AdapterRegistry()
-
- def _init_registrations(self):
- self._utility_registrations = {}
- self._adapter_registrations = {}
- self._subscription_registrations = []
- self._handler_registrations = []
-
- def _getBases(self):
- # Subclasses might override
- return self.__dict__.get('__bases__', ())
-
- def _setBases(self, bases):
- # Subclasses might override
- self.adapters.__bases__ = tuple([
- base.adapters for base in bases])
- self.utilities.__bases__ = tuple([
- base.utilities for base in bases])
- self.__dict__['__bases__'] = tuple(bases)
-
- __bases__ = property(
- lambda self: self._getBases(),
- lambda self, bases: self._setBases(bases),
- )
-
- def registerUtility(self, component=None, provided=None, name=u'', info=u'',
- event=True, factory=None):
- if factory:
- if component:
- raise TypeError("Can't specify factory and component.")
- component = factory()
-
- if provided is None:
- provided = _getUtilityProvided(component)
-
- reg = self._utility_registrations.get((provided, name))
- if reg is not None:
- if reg[:2] == (component, info):
- # already registered
- return
- self.unregisterUtility(reg[0], provided, name)
-
- subscribed = False
- for ((p, _), data) in self._utility_registrations.iteritems():
- if p == provided and data[0] == component:
- subscribed = True
- break
-
- self._utility_registrations[(provided, name)] = component, info, factory
- self.utilities.register((), provided, name, component)
-
- if not subscribed:
- self.utilities.subscribe((), provided, component)
-
- if event:
- notify(Registered(
- UtilityRegistration(self, provided, name, component, info,
- factory)
- ))
-
- def unregisterUtility(self, component=None, provided=None, name=u'',
- factory=None):
- if factory:
- if component:
- raise TypeError("Can't specify factory and component.")
- component = factory()
-
- if provided is None:
- if component is None:
- raise TypeError("Must specify one of component, factory and "
- "provided")
- provided = _getUtilityProvided(component)
-
- old = self._utility_registrations.get((provided, name))
- if (old is None) or ((component is not None) and
- (component != old[0])):
- return False
-
- if component is None:
- component = old[0]
-
- # Note that component is now the old thing registered
-
- del self._utility_registrations[(provided, name)]
- self.utilities.unregister((), provided, name)
-
- subscribed = False
- for ((p, _), data) in self._utility_registrations.iteritems():
- if p == provided and data[0] == component:
- subscribed = True
- break
-
- if not subscribed:
- self.utilities.unsubscribe((), provided, component)
-
- notify(Unregistered(
- UtilityRegistration(self, provided, name, component, *old[1:])
- ))
-
- return True
-
- def registeredUtilities(self):
- for ((provided, name), data
- ) in self._utility_registrations.iteritems():
- yield UtilityRegistration(self, provided, name, *data)
-
- def queryUtility(self, provided, name=u'', default=None):
- return self.utilities.lookup((), provided, name, default)
-
- def getUtility(self, provided, name=u''):
- utility = self.utilities.lookup((), provided, name)
- if utility is None:
- raise ComponentLookupError(provided, name)
- return utility
-
- def getUtilitiesFor(self, interface):
- for name, utility in self.utilities.lookupAll((), interface):
- yield name, utility
-
- def getAllUtilitiesRegisteredFor(self, interface):
- return self.utilities.subscriptions((), interface)
-
- def registerAdapter(self, factory, required=None, provided=None, name=u'',
- info=u'', event=True):
- if provided is None:
- provided = _getAdapterProvided(factory)
- required = _getAdapterRequired(factory, required)
- self._adapter_registrations[(required, provided, name)
- ] = factory, info
- self.adapters.register(required, provided, name, factory)
-
- if event:
- notify(Registered(
- AdapterRegistration(self, required, provided, name,
- factory, info)
- ))
-
-
- def unregisterAdapter(self, factory=None,
- required=None, provided=None, name=u'',
- ):
- if provided is None:
- if factory is None:
- raise TypeError("Must specify one of factory and provided")
- provided = _getAdapterProvided(factory)
-
- if (required is None) and (factory is None):
- raise TypeError("Must specify one of factory and required")
-
- required = _getAdapterRequired(factory, required)
- old = self._adapter_registrations.get((required, provided, name))
- if (old is None) or ((factory is not None) and
- (factory != old[0])):
- return False
-
- del self._adapter_registrations[(required, provided, name)]
- self.adapters.unregister(required, provided, name)
-
- notify(Unregistered(
- AdapterRegistration(self, required, provided, name,
- *old)
- ))
-
- return True
-
- def registeredAdapters(self):
- for ((required, provided, name), (component, info)
- ) in self._adapter_registrations.iteritems():
- yield AdapterRegistration(self, required, provided, name,
- component, info)
-
- def queryAdapter(self, object, interface, name=u'', default=None):
- return self.adapters.queryAdapter(object, interface, name, default)
-
- def getAdapter(self, object, interface, name=u''):
- adapter = self.adapters.queryAdapter(object, interface, name)
- if adapter is None:
- raise ComponentLookupError(object, interface, name)
- return adapter
-
- def queryMultiAdapter(self, objects, interface, name=u'', default=None):
- return self.adapters.queryMultiAdapter(
- objects, interface, name, default)
-
- def getMultiAdapter(self, objects, interface, name=u''):
- adapter = self.adapters.queryMultiAdapter(objects, interface, name)
- if adapter is None:
- raise ComponentLookupError(objects, interface, name)
- return adapter
-
- def getAdapters(self, objects, provided):
- for name, factory in self.adapters.lookupAll(
- map(providedBy, objects),
- provided):
- adapter = factory(*objects)
- if adapter is not None:
- yield name, adapter
-
- def registerSubscriptionAdapter(self,
- factory, required=None, provided=None,
- name=u'', info=u'',
- event=True):
- if name:
- raise TypeError("Named subscribers are not yet supported")
- if provided is None:
- provided = _getAdapterProvided(factory)
- required = _getAdapterRequired(factory, required)
- self._subscription_registrations.append(
- (required, provided, name, factory, info)
- )
- self.adapters.subscribe(required, provided, factory)
-
- if event:
- notify(Registered(
- SubscriptionRegistration(self, required, provided, name,
- factory, info)
- ))
-
- def registeredSubscriptionAdapters(self):
- for data in self._subscription_registrations:
- yield SubscriptionRegistration(self, *data)
-
- def unregisterSubscriptionAdapter(self, factory=None,
- required=None, provided=None, name=u'',
- ):
- if name:
- raise TypeError("Named subscribers are not yet supported")
- if provided is None:
- if factory is None:
- raise TypeError("Must specify one of factory and provided")
- provided = _getAdapterProvided(factory)
-
- if (required is None) and (factory is None):
- raise TypeError("Must specify one of factory and required")
-
- required = _getAdapterRequired(factory, required)
-
- if factory is None:
- new = [(r, p, n, f, i)
- for (r, p, n, f, i)
- in self._subscription_registrations
- if not (r == required and p == provided)
- ]
- else:
- new = [(r, p, n, f, i)
- for (r, p, n, f, i)
- in self._subscription_registrations
- if not (r == required and p == provided and f == factory)
- ]
-
- if len(new) == len(self._subscription_registrations):
- return False
-
-
- self._subscription_registrations[:] = new
- self.adapters.unsubscribe(required, provided, factory)
-
- notify(Unregistered(
- SubscriptionRegistration(self, required, provided, name,
- factory, '')
- ))
-
- return True
-
- def subscribers(self, objects, provided):
- return self.adapters.subscribers(objects, provided)
-
- def registerHandler(self,
- factory, required=None,
- name=u'', info=u'',
- event=True):
- if name:
- raise TypeError("Named handlers are not yet supported")
- required = _getAdapterRequired(factory, required)
- self._handler_registrations.append(
- (required, name, factory, info)
- )
- self.adapters.subscribe(required, None, factory)
-
- if event:
- notify(Registered(
- HandlerRegistration(self, required, name, factory, info)
- ))
-
- def registeredHandlers(self):
- for data in self._handler_registrations:
- yield HandlerRegistration(self, *data)
-
- def unregisterHandler(self, factory=None, required=None, name=u''):
- if name:
- raise TypeError("Named subscribers are not yet supported")
-
- if (required is None) and (factory is None):
- raise TypeError("Must specify one of factory and required")
-
- required = _getAdapterRequired(factory, required)
-
- if factory is None:
- new = [(r, n, f, i)
- for (r, n, f, i)
- in self._handler_registrations
- if r != required
- ]
- else:
- new = [(r, n, f, i)
- for (r, n, f, i)
- in self._handler_registrations
- if not (r == required and f == factory)
- ]
-
- if len(new) == len(self._handler_registrations):
- return False
-
- self._handler_registrations[:] = new
- self.adapters.unsubscribe(required, None, factory)
-
- notify(Unregistered(
- HandlerRegistration(self, required, name, factory, '')
- ))
-
- return True
-
- def handle(self, *objects):
- self.adapters.subscribers(objects, None)
-
-
-def _getUtilityProvided(component):
- provided = list(providedBy(component))
- if len(provided) == 1:
- return provided[0]
- raise TypeError(
- "The utility doesn't provide a single interface "
- "and no provided interface was specified.")
-
-def _getAdapterProvided(factory):
- provided = list(implementedBy(factory))
- if len(provided) == 1:
- return provided[0]
- raise TypeError(
- "The adapter factory doesn't implement a single interface "
- "and no provided interface was specified.")
-
-
-classTypes = type, types.ClassType
-def _getAdapterRequired(factory, required):
- if required is None:
- try:
- required = factory.__component_adapts__
- except AttributeError:
- raise TypeError(
- "The adapter factory doesn't have a __component_adapts__ "
- "attribute and no required specifications were specified"
- )
- elif ISpecification.providedBy(required):
- raise TypeError("the required argument should be a list of "
- "interfaces, not a single interface")
-
- result = []
- for r in required:
- if r is None:
- r = Interface
- elif not ISpecification.providedBy(r):
- if isinstance(r, classTypes):
- r = implementedBy(r)
- else:
- raise TypeError("Required specification must be a "
- "specification or class."
- )
- result.append(r)
- return tuple(result)
-
-
-class UtilityRegistration(object):
-
- implements(IUtilityRegistration)
-
- def __init__(self, registry, provided, name, component, doc, factory=None):
- (self.registry, self.provided, self.name, self.component, self.info,
- self.factory
- ) = registry, provided, name, component, doc, factory
-
- def __repr__(self):
- return '%s(%r, %s, %r, %s, %r, %r)' % (
- self.__class__.__name__,
- self.registry,
- getattr(self.provided, '__name__', None), self.name,
- getattr(self.component, '__name__', `self.component`),
- self.factory, self.info,
- )
-
- def __cmp__(self, other):
- return cmp(self.__repr__(), other.__repr__())
-
-class AdapterRegistration(object):
-
- implements(IAdapterRegistration)
-
- def __init__(self, registry, required, provided, name, component, doc):
- (self.registry, self.required, self.provided, self.name,
- self.factory, self.info
- ) = registry, required, provided, name, component, doc
-
- def __repr__(self):
- return '%s(%r, %s, %s, %r, %s, %r)' % (
- self.__class__.__name__,
- self.registry,
- '[' + ", ".join([r.__name__ for r in self.required]) + ']',
- getattr(self.provided, '__name__', None), self.name,
- getattr(self.factory, '__name__', `self.factory`), self.info,
- )
-
- def __cmp__(self, other):
- return cmp(self.__repr__(), other.__repr__())
-
-class SubscriptionRegistration(AdapterRegistration):
-
- implementsOnly(ISubscriptionAdapterRegistration)
-
-class HandlerRegistration(AdapterRegistration):
-
- implementsOnly(IHandlerRegistration)
-
- def __init__(self, registry, required, name, handler, doc):
- (self.registry, self.required, self.name, self.handler, self.info
- ) = registry, required, name, handler, doc
-
- @property
- def factory(self):
- return self.handler
-
- provided = None
-
- def __repr__(self):
- return '%s(%r, %s, %r, %s, %r)' % (
- self.__class__.__name__,
- self.registry,
- '[' + ", ".join([r.__name__ for r in self.required]) + ']',
- self.name,
- getattr(self.factory, '__name__', `self.factory`), self.info,
- )
-
-
@adapter(IUtilityRegistration, IRegistrationEvent)
def dispatchUtilityRegistrationEvent(registration, event):
handle(registration.component, event)
Modified: zope.component/trunk/src/zope/component/tests.py
===================================================================
--- zope.component/trunk/src/zope/component/tests.py 2011-09-15 05:55:00 UTC (rev 122812)
+++ zope.component/trunk/src/zope/component/tests.py 2011-09-15 06:08:23 UTC (rev 122813)
@@ -213,6 +213,7 @@
We don't know anything about the default service manager, except that it
is an `IComponentLookup`.
+ >>> from zope.component.interfaces import IComponentLookup
>>> IComponentLookup.providedBy(component.getSiteManager())
True
@@ -244,11 +245,11 @@
Using a context that is not adaptable to `IComponentLookup` should fail.
- >>> component.getSiteManager(ob) #doctest: +NORMALIZE_WHITESPACE
+ >>> component.getSiteManager(ob) #doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
Traceback (most recent call last):
...
ComponentLookupError: ('Could not adapt', <instance Ob>,
- <InterfaceClass zope.component.interfaces.IComponentLookup>)
+ <InterfaceClass zope...interfaces.IComponentLookup>)
"""
def testAdapterInContext(self):
@@ -946,7 +947,7 @@
... print "| Factory 2 is here"
>>> class Event(object):
... zope.interface.implements(I)
- >>> from zope.component.registry import Components
+ >>> from zope.interface.registry import Components
>>> registry = Components()
>>> registry.registerHandler(factory1, [I,])
>>> registry.registerHandler(factory2, [I,])
@@ -985,7 +986,7 @@
Now, let's create two registries and set up the bases hierarchy::
- >>> from zope.component.registry import Components
+ >>> from zope.interface.registry import Components
>>> sm1 = Components('sm1', bases=(gsm, ))
>>> sm1_1 = Components('sm1_1', bases=(sm1, ))
@@ -1063,8 +1064,8 @@
We've observed utilities getting left in _subscribers when they
get unregistered.
- >>> import zope.component.registry
- >>> reg = zope.component.registry.Components()
+ >>> import zope.interface.registry
+ >>> reg = zope.interface.registry.Components()
>>> class C:
... def __init__(self, name):
... self.name = name
@@ -1096,7 +1097,7 @@
method to get the registry where to register the components. This makes
possible to hook ``getSiteManager`` before loading a ZCML file:
- >>> from zope.component.registry import Components
+ >>> from zope.interface.registry import Components
>>> registry = Components()
>>> def dummy(context=None):
... return registry
@@ -1719,9 +1720,6 @@
setUp=setUp, tearDown=tearDown),
doctest.DocFileSuite('factory.txt',
setUp=setUp, tearDown=tearDown),
- doctest.DocFileSuite('registry.txt', checker=checker,
- setUp=setUpRegistryTests,
- tearDown=tearDownRegistryTests),
doctest.DocFileSuite('hooks.txt',checker=checker,
setUp=setUp, tearDown=tearDown),
doctest.DocFileSuite('event.txt',
More information about the checkins
mailing list