pythoninterfacezopezope.interface

Purpose of Zope Interfaces?


I have started using Zope interfaces in my code, and as of now, they are really only documentation. I use them to specify what attributes the class should possess, explicitly implement them in the appropriate classes and explicitly check for them where I expect one. This is fine, but I would like them to do more if possible, such as actually verify that the class has implemented the interface, instead of just verifying that I have said that the class implements the interface. I have read the zope wiki a couple of times, but still cannot see much more use for interfaces than what I am currently doing. So, my question is what else can you use these interfaces for, and how do you use them for more.


Solution

  • You can actually test if your object or class implements your interface. For that you can use verify module (you would normally use it in your tests):

    >>> from zope.interface import Interface, Attribute, implements
    >>> class IFoo(Interface):
    ...     x = Attribute("The X attribute")
    ...     y = Attribute("The Y attribute")
    
    >>> class Foo(object):
    ...     implements(IFoo)
    ...     x = 1
    ...     def __init__(self):
    ...         self.y = 2
    
    >>> from zope.interface.verify import verifyObject
    >>> verifyObject(IFoo, Foo())
    True
    
    >>> from zope.interface.verify import verifyClass
    >>> verifyClass(IFoo, Foo)
    True
    

    Interfaces can also be used for setting and testing invariants. You can find more information here:

    http://www.muthukadan.net/docs/zca.html#interfaces