[Grok-dev] Simple adapter question

Martin Aspeli optilude+lists at gmail.com
Thu Mar 5 14:26:16 EST 2009

Carsten Senger wrote:
> Hallo Jan,
> Jan Ulrich Hasecke schrieb:
>> Hash: SHA1
>> Hi,
>> browsing the docs I have a question concerning adapters.
>> import grok
>> from zope import interface
>> class Fireplace(grok.Model):
>>     pass
>> class Cave(grok.Model):
>>     pass
>> class IHome(interface.Interface):
>>     pass
>> class Home(grok.MultiAdapter):
>>     grok.adapts(Cave, Fireplace)
>>     grok.implements(IHome)
>>     def __init__(self, cave, fireplace):
>>         self.cave = cave
>>         self.fireplace = fireplace
>> home = IHome(cave, fireplace)

This looks fishy to me. Unless Grok is doing something very evil, this 
won't work: it'll try to adapt `cave` to IHome, and if that fails, it'll 
fall back to the second argument 'fireplace'.

I think what you want is:

  home = getMultiAdapter((cave, fireplace), IHome)

>> Why is there an IHome in the last line? I would think that
>> home = Home(cave, fireplace)
>> would create a home-instance.

It does, and in this case, the two are probably equivalent. "Calling" 
the interface (for a single-adapter!) or using 
getAdapter/getMultiAdapter, means "Get the adapter from what I give you, 
to the interface I ask for". If there was a more specific adapter to 
IHome, then you'd get that one instead.

If you can, find Brandon Craig Rhodes "using grok to walk like a duck" 
talk on video and watch it. :)


Author of `Professional Plone Development`, a book for developers who
want to work with Plone. See http://martinaspeli.net/plone-book

More information about the Grok-dev mailing list