Interfaces (a la PEP 245 and Zope)

Terry Hancock hancock at
Fri Aug 1 08:00:05 CEST 2003

So, how did the chips fall on implementing interfaces in Python?  :-)

I've been using the Interface module that is included in Zope, and
although, I've found it useful, there are some cases I don't seem to
find a good solution for.  To illustrate, I'll just describe my current

I want to define an object which implements a variety of methods
and attributes required by Zope, and use it to wrap a simpler object
which might be written by a plugin author.  The rest of my code
assumes that this plugin will conform to a given interface, so I want
to check that it does (to make life easier for the plugin developer).

I'd *like* to do something like this:

class EditorAPI(Base):
    Mandatory interface for Editor plugins.
    # Defines stuff that an editor must have to satisfy the rest
    # of the program.

class Editor(Folder):
    Zope Narya-Editor object is base for all editors.
    meta_type = "Narya-Editor"
    __implements__ = 'EditorAPI'
    def __init__(self, id, editor_core=None):
        Wrap an editor plug-in into a Narya-Editor instance.
        for key in editor_core.__dict__.keys():
            setattr(self, key, getattr(editor_core, key))

        if EditorAPI.isImplementedBy(self):
            raise BrokenImplementation(
                "Editor plugin '%s' fails implementation test." % editor_core.title)
            self.__implements__ = EditorAPI

BUT, .isImplementedBy(self) only seems to check to see if
self.__implements__  contains an assertion for the interface.

What I really want is a thorough check, along the lines of

Interface.verify.verify_class_implementation(iface, klass)

does.  But that's no good, because this object wasn't created by
a simple class statement -- we're creating it dynamically in the
__init__() method.

Now of course, I could pick through the Interface module and
write a check that resembles the verification that it does, but it seems to 
me that there ought to be a simpler solution (and if I were going to
do that, I should probably really be improving the Interface module
rather than putting the code in my package).

So, am I missing some existing way to do this?


Terry Hancock
Anansi Spaceworks

More information about the Python-list mailing list