Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 529
Luiz Geron Avatar asked Oct 11 '22 08:10

Luiz Geron


2 Answers

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.

like image 176
Martijn Pieters Avatar answered Oct 20 '22 05:10

Martijn Pieters


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.

like image 30
Perkins Avatar answered Oct 20 '22 05:10

Perkins