Interfaces

This chapter contains information about using zope.interface with Pyramid.

Dynamically Compute the Interfaces Provided by an Object

(Via Marius Gedminas)

When persisting the interfaces that are provided by an object in a pickle or in ZODB is not reasonable for your application, you can use this trick to dynamically return the set of interfaces provided by an object based on other data in an instance of the object:

 1from zope.interface.declarations import Provides
 2
 3from mypackage import interfaces
 4
 5class MyClass(object):
 6
 7    color = None
 8
 9    @property
10    def __provides__(self):
11        # black magic happens here: we claim to provide the right IFrob
12        # subinterface depending on the value of the ``color`` attribute.
13        iface = getattr(interfaces, 'I%sFrob' % self.color.title(),
14                        interfaces.IFrob))
15        return Provides(self.__class__, iface)

If you need the object to implement more than one interface, use Provides(self.__class__, iface1, iface2, ...).