how do I get a list of classes that implement an interface? (zope.interface)
The question says everything. Or am I trying to use zope.interface
for the wrong purpose?
What I need is basically the One Way To Do It for registering classes that implement a certain functionality (Widgets or Portlets for a CMS). Basically like django does with its ModelAdmin classes, but not automatic and not开发者_C百科 magic.
This is what the zope.component
architecture solves, but you must register all uses of an interface. By itself, zope.interface
does not keep track of what objects implement a given interface.
What you are looking for is utility registrations; all implementations of a given service as defined by an interface.
The simplest approach is to decorate zope.interface.declarations.classImplements
(and its alias zope.interface.classImplements
).
from zope import interface as i
from collections import defaultdict
oclassImplements = i.classImplements
registry = defaultdict(list)
def classImplements(cls, *interfaces):
for a in interfaces:
registry[a].append(cls)
return oclassImplements(cls, *interfaces)
i.classImplements = i.declarations.classImplements = classImplements
Note that you must do this before the interfaces you want to catch are implemented, usually it's best to do this before importing anything else.
精彩评论