how do I get a list of classes that implement an interface? (zope.interface)

2.2k Views Asked by At

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 magic.

2

There are 2 best solutions below

0
On

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.

4
On

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.