Adapter Registration APIs

This document covers a specific subset of the APIs in zope.component.

zope.component.provideAdapter(factory, adapts=None, provides=None, name=u'')[source]

Register an adapter globally

An adapter is registered to provide an interface with a name for some number of object types. If a factory implements only one interface, then the provides argument can be omitted and the provided interface will be used. (In this case, a provides argument can still be provided to provide a less specific interface.)

If the factory has an adapts declaration, then the adapts argument can be omitted and the declaration will be used. (An adapts argument can be provided to override the declaration.)

See also

Function provideAdapter for notes, and IComponentRegistrationConvenience for the defining interface.

zope.component.provideHandler(factory, adapts=None)[source]

Register a handler

Handlers are subscription adapter factories that don’t produce anything. They do all of their work when called. Handlers are typically used to handle events.

If the handler has an adapts declaration, then the adapts argument can be omitted and the declaration will be used. (An adapts argument can be provided to override the declaration.)

See also

Function provideHandler for notes, and IComponentRegistrationConvenience for the defining interface.

zope.component.provideSubscriptionAdapter(factory, adapts=None, provides=None)[source]

Register a subscription adapter

A subscription adapter is registered to provide an interface for some number of object types. If a factory implements only one interface, then the provides argument can be omitted and the provided interface will be used. (In this case, a provides argument can still be provided to provide a less specific interface.)

If the factory has an adapts declaration, then the adapts argument can be omitted and the declaration will be used. (An adapts argument can be provided to override the declaration.)

See also

Function provideSubscriptionAdapter for notes, and IComponentRegistrationConvenience for the defining interface.

Conforming Adapter Lookup

zope.component.getAdapterInContext(object, interface, context)[source]

Get a special adapter to an interface for an object

Note

This method should only be used if a custom context needs to be provided to provide custom component lookup. Otherwise, call the interface, as in:

interface(object)

Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, raises ComponentLookupError.

If the object has a __conform__ method, this method will be called with the requested interface. If the method returns a non-None value, that value will be returned. Otherwise, if the object already implements the interface, the object will be returned.

See also

Function getAdapterInContext for notes, and IComponentArchitecture for the defining interface.

zope.component.queryAdapterInContext(object, interface, context, default=None)[source]

Look for a special adapter to an interface for an object

Note

This method should only be used if a custom context needs to be provided to provide custom component lookup. Otherwise, call the interface, as in:

interface(object, default)

Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, returns the default.

If the object has a __conform__ method, this method will be called with the requested interface. If the method returns a non-None value, that value will be returned. Otherwise, if the object already implements the interface, the object will be returned.

See also

Function queryAdapterInContext for notes, and IComponentArchitecture for the defining interface.

The getAdapterInContext() and queryAdapterInContext() APIs first check the context object to see if it already conforms to the requested interface. If so, the object is returned immediately. Otherwise, the adapter factory is looked up in the site manager, and called.

Let’s start by creating a component that supports the __conform__() method:

>>> from zope.interface import implementer
>>> from zope.component.tests.examples import I1
>>> from zope.component.tests.examples import I2
>>> @implementer(I1)
... class Component(object):
...     def __conform__(self, iface, default=None):
...         if iface == I2:
...             return 42
>>> ob = Component()

We also gave the component a custom representation, so it will be easier to use in these tests.

We now have to create a site manager (other than the default global one) with which we can register adapters for I1.

>>> from zope.component.globalregistry import BaseGlobalComponents
>>> sitemanager = BaseGlobalComponents()

Now we create a new context that knows how to get to our custom site manager.

>>> from zope.component.tests.examples import ConformsToIComponentLookup
>>> context = ConformsToIComponentLookup(sitemanager)

If an object implements the interface you want to adapt to, getAdapterInContext() should simply return the object.

>>> from zope.component import getAdapterInContext
>>> from zope.component import queryAdapterInContext
>>> getAdapterInContext(ob, I1, context) is ob
True
>>> queryAdapterInContext(ob, I1, context) is ob
True

If an object conforms to the interface you want to adapt to, getAdapterInContext() should simply return the conformed object.

>>> getAdapterInContext(ob, I2, context)
42
>>> queryAdapterInContext(ob, I2, context)
42

If an adapter isn’t registered for the given object and interface, and you provide no default, the getAdapterInContext API raises ComponentLookupError:

>>> from zope.interface import Interface
>>> class I4(Interface):
...     pass

>>> getAdapterInContext(ob, I4, context)
Traceback (most recent call last):
...
ComponentLookupError: (<Component implementing 'I1'>,
                       <InterfaceClass ...I4>)

While the queryAdapterInContext API returns the default:

>>> queryAdapterInContext(ob, I4, context, 44)
44

If you ask for an adapter for which something’s registered you get the registered adapter:

>>> from zope.component.tests.examples import I3
>>> sitemanager.registerAdapter(lambda x: 43, (I1,), I3, '')
>>> getAdapterInContext(ob, I3, context)
43
>>> queryAdapterInContext(ob, I3, context)
43

Named Adapter Lookup

zope.component.getAdapter(object, interface=<InterfaceClass zope.interface.Interface>, name=u'', context=None)[source]

Get a named adapter to an interface for an object

Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, raises ComponentLookupError.

See also

Function getAdapter for notes, and IComponentArchitecture for the defining interface.

zope.component.queryAdapter(object, interface=<InterfaceClass zope.interface.Interface>, name=u'', default=None, context=None)[source]

Look for a named adapter to an interface for an object

Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, returns the default.

See also

Function queryAdapter for notes, and IComponentArchitecture for the defining interface.

The getAdapter and queryAdapter API functions are similar to {get|query}AdapterInContext() functions, except that they do not care about the __conform__() but also handle named adapters. (Actually, the name is a required argument.)

If no adapter is registered for the given object, interface, and name, getAdapter raises ComponentLookupError, while queryAdapter returns the default:

>>> from zope.component import getAdapter
>>> from zope.component import queryAdapter
>>> from zope.component.tests.examples import I2
>>> from zope.component.tests.examples import ob
>>> getAdapter(ob, I2, '')
Traceback (most recent call last):
...
ComponentLookupError: (<instance Ob>,
                       <InterfaceClass zope.component.tests.examples.I2>,
                       '')
>>> queryAdapter(ob, I2, '', '<default>')
'<default>'

The ‘requires’ argument to registerAdapter must be a sequence, rather than a single interface:

>>> from zope.component import getGlobalSiteManager
>>> from zope.component.tests.examples import Comp
>>> gsm = getGlobalSiteManager()
>>> gsm.registerAdapter(Comp, I1, I2, '')
Traceback (most recent call last):
  ...
TypeError: the required argument should be a list of interfaces, not a single interface

After register an adapter from I1 to I2 with the global site manager:

>>> from zope.component import getGlobalSiteManager
>>> from zope.component.tests.examples import Comp
>>> gsm = getGlobalSiteManager()
>>> gsm.registerAdapter(Comp, (I1,), I2, '')

We can access the adapter using the getAdapter() API:

>>> adapted = getAdapter(ob, I2, '')
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True
>>> adapted = queryAdapter(ob, I2, '')
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True

If we search using a non-anonymous name, before registering:

>>> getAdapter(ob, I2, 'named')
Traceback (most recent call last):
...
ComponentLookupError: (<instance Ob>,
                       <InterfaceClass ....I2>,
                       'named')
>>> queryAdapter(ob, I2, 'named', '<default>')
'<default>'

After registering under that name:

>>> gsm.registerAdapter(Comp, (I1,), I2, 'named')
>>> adapted = getAdapter(ob, I2, 'named')
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True
>>> adapted = queryAdapter(ob, I2, 'named')
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True

Invoking an Interface to Perform Adapter Lookup

zope.component registers an adapter hook with zope.interface.interface.adapter_hooks, allowing a convenient spelling for adapter lookup: just “call” the interface, passing the context:

>>> adapted = I2(ob)
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True

If the lookup fails, we get a TypeError:

>>> I2(object())
Traceback (most recent call last):
...
TypeError: ('Could not adapt'...

unless we pass a default:

>>> marker = object()
>>> adapted = I2(object(), marker)
>>> adapted is marker
True

Registering Adapters For Arbitrary Objects

Providing an adapter for None says that your adapter can adapt anything to I2.

>>> gsm.registerAdapter(Comp, (None,), I2, '')
>>> adapter = I2(ob)
>>> adapter.__class__ is Comp
True
>>> adapter.context is ob
True

It can really adapt any arbitrary object:

>>> something = object()
>>> adapter = I2(something)
>>> adapter.__class__ is Comp
True
>>> adapter.context is something
True

Looking Up Adapters Using Multiple Objects

zope.component.getMultiAdapter(objects, interface=<InterfaceClass zope.interface.Interface>, name=u'', context=None)[source]

Look for a multi-adapter to an interface for an objects

Returns a multi-adapter that can adapt objects to interface. If a matching adapter cannot be found, raises ComponentLookupError.

The name consisting of an empty string is reserved for unnamed adapters. The unnamed adapter methods will often call the named adapter methods with an empty string for a name.

See also

Function getMultiAdapter for notes, and IComponentArchitecture for the defining interface.

zope.component.queryMultiAdapter(objects, interface=<InterfaceClass zope.interface.Interface>, name=u'', default=None, context=None)[source]

Look for a multi-adapter to an interface for objects

Returns a multi-adapter that can adapt objects to interface. If a matching adapter cannot be found, returns the default.

The name consisting of an empty string is reserved for unnamed adapters. The unnamed adapter methods will often call the named adapter methods with an empty string for a name.

See also

Function queryMultiAdapter for notes, and IComponentArchitecture for the defining interface.

Multi-adapters adapt one or more objects to another interface. To make this demonstration non-trivial, we need to create a second object to be adapted:

>>> from zope.component.tests.examples import Ob2
>>> ob2 = Ob2()

As with regular adapters, if an adapter isn’t registered for the given objects and interface, the getMultiAdapter() API raises zope.interface.interfaces.ComponentLookupError:

>>> from zope.component import getMultiAdapter
>>> getMultiAdapter((ob, ob2), I3)
Traceback (most recent call last):
...
ComponentLookupError:
((<instance Ob>, <instance Ob2>),
 <InterfaceClass zope.component.tests.examples.I3>,
 u'')

while the queryMultiAdapter() API returns the default:

>>> from zope.component import queryMultiAdapter
>>> queryMultiAdapter((ob, ob2), I3, default='<default>')
'<default>'

Note that name is not a required attribute here.

To test multi-adapters, we also have to create an adapter class that handles to context objects:

>>> from zope.interface import implementer
>>> @implementer(I3)
... class DoubleAdapter(object):
...     def __init__(self, first, second):
...         self.first = first
...         self.second = second

Now we can register the multi-adapter:

>>> from zope.component import getGlobalSiteManager
>>> getGlobalSiteManager().registerAdapter(DoubleAdapter, (I1, I2), I3, '')

Notice how the required interfaces are simply provided by a tuple.

Now we can get the adapter:

>>> adapter = getMultiAdapter((ob, ob2), I3)
>>> adapter.__class__ is DoubleAdapter
True
>>> adapter.first is ob
True
>>> adapter.second is ob2
True

Finding More Than One Adapter

zope.component.getAdapters(objects, provided, context=None)[source]

Look for all matching adapters to a provided interface for objects

Return a list of adapters that match. If an adapter is named, only the most specific adapter of a given name is returned.

See also

Function getAdapters for notes, and IComponentArchitecture for the defining interface.

It is sometimes desireable to get a list of all adapters that are registered for a particular output interface, given a set of objects.

Let’s register some adapters first:

>>> class I5(I1):
...     pass
>>> gsm.registerAdapter(Comp, [I1], I5, '')
>>> gsm.registerAdapter(Comp, [None], I5, 'foo')

Now we get all the adapters that are registered for ob that provide I5 (note that the names are always text strings, meaning that on Python 2 the names will be unicode):

>>> from zope.component import getAdapters
>>> adapters = sorted(getAdapters((ob,), I5))
>>> [(str(name), adapter.__class__.__name__) for name, adapter in adapters]
[('', 'Comp'), ('foo', 'Comp')]
>>> try:
...    text = unicode
... except NameError:
...    text = str # Python 3
>>> [isinstance(name, text) for name, _ in adapters]
[True, True]

Note that the output doesn’t include None values. If an adapter factory returns None, it is as if it wasn’t present.

>>> gsm.registerAdapter(lambda context: None, [I1], I5, 'nah')
>>> adapters = sorted(getAdapters((ob,), I5))
>>> [(str(name), adapter.__class__.__name__) for name, adapter in adapters]
[('', 'Comp'), ('foo', 'Comp')]

Subscription Adapters

zope.component.subscribers(objects, interface, context=None)[source]

Get subscribers

Subscribers are returned that provide the provided interface and that depend on and are computed from the sequence of required objects.

See also

Function subscribers for notes, and IComponentArchitecture for the defining interface.

Event handlers

zope.component.handle(*objects)[source]

Call all of the handlers for the given objects

Handlers are subscription adapter factories that don’t produce anything. They do all of their work when called. Handlers are typically used to handle events.

See also

Function handle for notes, and IComponentArchitecture for the defining interface.

Helpers for Declaring / Testing Adapters

zope.component.adapter(*interfaces)[source]

Decorator that declares that the decorated object adapts the given interfaces.

This is commonly used in conjunction with zope.interface.implementer to declare what adapting the interfaces will provide.

zope.component.adaptedBy(ob)[source]

Return the interfaces that ob will adapt, as declared by adapter.

zope.component.adapts(*interfaces)[source]