[Zope3-dev] Adapter changes: calling interfaces to get adapters

Jim Fulton jim at zope.com
Sat Mar 6 13:10:30 EST 2004


I've added a __call__ method to Zope interfaces to provide
new way of getting adapters.

To adapt an object to an interface, you can now call the interface:

   adapter = iface(ob)

This will raise a TypeError if the adapter can't be found. You
can also provide a default value:

   adapter = iface(ob, None)
   if adapter is not None:
       ...

The semantics of interface call are based on PEP 246.  Interface
calls are syntactic sugar for the PEP 246 adapt function:

   iface(ob)       <===>  adapt(ob, iface)
   iface(ob, None) <===>  adapt(ob, iface, None)

(Note that the only distributed implementation of the
  adapt function of which I'm aware is that in
  PyProtocols.)

The semantics are a little different than those of
zope.component.getAdapter and zope.component.queryAdapter.
The zope.component methods *first* check whether an object
provides the desired interface, and return the object if it does.
Interface __call__ calls an object's __conform__ method, if it has one,
before checking whether the object provides the interface.

Interfaces also have an PEP 246 __adapt__ method and a simple
adapter_hook registry for installing adapter-lookup mechanisms.
The zope.component package uses this mechanism to install it's
adapter-lookup. Future versions of PyProtocols will register
PyProtocol's adapter system.  It will be possible to use both
zope.component adapters and PyProtocols adapters in the same
application.

(An interesting consequence of the change is that applications that
  only need adapter lookup, need not depend on zope.component, at
  least not directly.)

I've changed most getAdapter and queryAdapter calls in Zope to
use interface calls instead.

I propose that interface call should be used for all *simple* adapter
lookups.  Of course, there are many advanced adapter lookup cases
for which component-architecture calls are still used, including:

- Named adapters

- Multi-adapters

- Adapter lookups from specific contexts, used when
   you need to provide explicit control over where adapters
   are looked up in multi-site systems.

It's worth noting some major semantic difference between simple adapter
lookups and multi- or named-adapter lookups.  For simple lookups, and
only for simple lookups, and object is it's own adapter if it provides
the desired interface. Also, an object's __conform__ method, if present,
is only used for simple-adapter lookups.

Jim

-- 
Jim Fulton           mailto:jim at zope.com       Python Powered!
CTO                  (540) 361-1714            http://www.python.org
Zope Corporation     http://www.zope.com       http://www.zope.org




More information about the Zope3-dev mailing list