[BlueBream] Chaining Adaptors

Mike Rhodes mike at netsight.co.uk
Wed Jul 7 07:27:23 EDT 2010


Hi,

I've a question about whether the ZCA will chain adapters when trying to 
adapt from one type to another. I couldn't see a specific Zope Toolkit 
mailing list, so if this is the wrong list please feel free to berate me 
and point me toward the correct one!

The easiest way to explain my question is probably with some code.

Essentially what I am trying to do is to work out whether the ZCA can 
"chain" adapters together when required to satisfy an adaptation 
request. In my example, you need to chain together two adapters: A->B 
then B->C.

==========================

from zope.interface import Interface, implements
from zope.component import adapts, getGlobalSiteManager

# I have three interfaces:
class IInterfaceA(Interface):
     pass
class IInterfaceB(Interface):
     pass
class IInterfaceC(Interface):
     pass

# Two adaptors between these interfaces:
class AdaptorAB(object):
     adapts(IInterfaceA)
     implements(IInterfaceB)

     def __init__(self, adaptee):
         pass

class AdaptorBC(object):
     adapts(IInterfaceB)
     implements(IInterfaceC)

     def __init__(self, adaptee):
         pass

# And finally, a class implementing IInterfaceA
class ClassA(object):
     implements(IInterfaceA)

# Register my adapters
gsm = getGlobalSiteManager()
gsm.registerAdapter(AdaptorAB, (IInterfaceA,), IInterfaceB)
gsm.registerAdapter(AdaptorBC, (IInterfaceB,), IInterfaceC)

objectA = ClassA()

# You can manually create the chain as follows, which works:
b_like = IInterfaceB(objectA)
c_like = IInterfaceC(b_like)

# But it appears that you cannot get the ZCA to resolve
# the required chain as this line produces an error:
c_like = IInterfaceC(objectA)

# c_like = getAdapter(objectA, IInterfaceC) also fails.

==========================

When you try to run the last line you get the error:

Traceback (most recent call last):
   File "zca_demo.py", line 44, in <module>
     c_like = IInterfaceC(objectA)
TypeError: ('Could not adapt', <__main__.ClassA object at 0x100686a10>, 
<InterfaceClass __main__.IInterfaceC>)


I thought that the ZCA could do this, so I'm wondering if there is 
something wrong with the above code which is prevent the ZCA doing it 
(e.g., is the shorthand IInterfaceC(objectA) incorrect?)

Thanks for your help,
Mike.

-- 
Netsight / www.netsight.co.uk
0117 909 0901 (ext. 23)


More information about the bluebream mailing list