added some experimental stuff for self-registering adapters using a metaclass

git-svn-id: svn://svn.cy55.de/Zope3/src/cybertools/trunk@2465 fd906abe-77d9-0310-91a1-e0d9ade77398
This commit is contained in:
helmutm 2008-03-21 13:11:12 +00:00
parent 2ff4d5ac22
commit 872fccc529
2 changed files with 49 additions and 0 deletions

View file

@ -56,3 +56,29 @@ class AdapterFactory(object):
if adapter is None: if adapter is None:
return None return None
return adapter(obj) return adapter(obj)
# self-registering adapters
adapters = AdapterFactory()
class AdapterType(type):
""" To be used as metaclass for self-registering adapters.
"""
def __init__(cls, name, bases, cdict):
super(AdapterType, cls).__init__(name, bases, cdict)
info = list(cdict.get('__adapterinfo__', (adapters, object, '')))
if len(info) < 2:
info.append(object)
if len(info) < 3:
info.append('')
factory, adapted, name = info
factory.register(cls, adapted, name)
class AdapterBase:
__metaclass__ = AdapterType

View file

@ -7,6 +7,10 @@ $Id$
To work with adapters we need at least two classes, one for objects To work with adapters we need at least two classes, one for objects
that we want to adapt to (the adapter's `context`) and one for the adapters. that we want to adapt to (the adapter's `context`) and one for the adapters.
Adapter Classes and Factories
=============================
>>> class Content(object): >>> class Content(object):
... pass ... pass
@ -100,3 +104,22 @@ example above.
>>> c2 >>> c2
<Content object ...> <Content object ...>
Self-registering Adapters
=========================
>>> from cybertools.util.adapter import adapters, AdapterBase
>>> stateful = AdapterFactory()
>>> class StateAdapter(AdapterBase):
... __adapterinfo__ = stateful, Content
... def __init__(self, context):
... self.context = context
... def setState(self, state):
... self.context._state = state
... def getState(self):
... return getattr(self.context, '_state', 'initial')
>>> stateful._registry
{(<class 'Content'>, ''): <class 'StateAdapter'>}