[Zope3-dev] Re: wildcard adapter

Marius Gedminas mgedmin at b4net.lt
Thu Jan 18 08:09:36 EST 2007


On Thu, Jan 18, 2007 at 08:53:36AM +0000, Chris Withers wrote:
> Philipp von Weitershausen wrote:
> >>If it is, then which of the following should I use to register a 
> >>generic adapter for any single object to an interface:
> >>
> >>provideAdapter(...,adapts=(None,),...)
> >
> >This one.
> 
> Given that you can register adapters for any class, whether or not it 
> implements any interface, this doesn't work as it should:
> 
> >>> from zope.component import provideAdapter
> >>> def adapter(*args): pass
> ...
> >>> from zope.interface import Interface
> >>> class ITest(Interface): pass
> ...
> >>> provideAdapter(adapter,adapts=(None,),provides=ITest)

It's a bit subtle.  The function you pass to provideAdapter is not the
adapter, it is an adapter factory.  Consider the difference between
classes and objects.  One is a factory for the other.  Adapters are
usually objects, and but you register classes with provideAdapter.

Now when you try to adapt anything to ITest, zope.component will call
your ``adapter`` function and then check the return value.  A return
value of None means "the adapter is not available", and results in a
TypeError you see here:

> >>> ITest(1)
> Traceback (most recent call last):
> ...
> TypeError: ('Could not adapt', 1, <InterfaceClass __main__.ITest>)

This is useful when you want to have an adapter that is available
conditionally.

Insert a print statement in your adapter function, and you will see that
it does get called:

  >>> from zope.component import provideAdapter
  >>> def myAdapter(*args):
  ...     print "Hi"
  ...
  >>> from zope.interface import Interface
  >>> class ITest(Interface): pass
  ...
  >>> provideAdapter(myAdapter,adapts=(None,),provides=ITest)
  >>> ITest(1)
  Hi
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  TypeError: ('Could not adapt', 1, <InterfaceClass __main__.ITest>)

> >I have no idea what a "generic" adapter is, but the zope.component API 
> >docs (== interfaces) are certainly complete in this sense. There are 
> >also doctests.
> 
> Where can I find the docs and interfaces you mention above? I looked 
> through both zope.interface and zope.component and obviously missed them :-(

src/zope/component/README.txt would be my guess.  I do not remember
what's inside, I learnt adapters by osmosis and occasional studying of
the source code.

Marius Gedminas
-- 
Change is inevitable, except from a vending machine.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.zope.org/pipermail/zope3-dev/attachments/20070118/8407df5a/attachment.bin


More information about the Zope3-dev mailing list