简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM