In a standalone python application, I use zope.interface, zope.component packages to register and access application adapters. I thought I could use the concept of a metaclass to register adapters from within the init method of the metaclass. This “automates” the adapter registration process. You see problems with this approach, for example. using the attributes that the zope package adds to the class? Thank you in advance for your entry.
from zope import component
from zope.interface import Interface, implements
class MetaclassAdapter(type):
def __init__(cls, clsname, bases, attrs):
super(MetaclassAdapter, cls).__init__(clsname, bases, attrs)
component.provideAdapter(cls, cls.__component_adapts__, cls.__implements_advice_data__[0][0])
class IDocument(Interface):
"""Document interface."""
def title():
pass
def author():
pass
def content():
pass
class IPrinter(Interface):
"""Printer interface."""
def write():
"""Print instance to ..."""
class Printer(object):
"""Adapt instances that provide IDocument interface to IPrinter.
Print document attributes to stdout.
"""
__metaclass__ = MetaclassAdapter
implements(IPrinter)
component.adapts(IDocument)
def __init__(self, context):
"""Store adapted instance that provides IDocument."""
self.context = context
def write(self):
"""Serialize document."""
print 'author: ', self.context.author()
print 'title: ', self.context.title()
print 'content: ', self.context.content()
class TextDocument(object):
implements(IDocument)
def __init__(self, author, title, content):
self._author = author
self._title = title
self._content = content
def title(self):
return self._title
def author(self):
return self._author
def content(self):
return self._content
IPrinter(TextDocument("Leo T.", "Short Stories", "Once upon a time...")).write()
source
share