Monday 13 September 2010

Zope Interfaces on Anonymous Functions.

Pretty old, but It's something I've not come across yet as a Zope coder. I was reading about Zope Interfaces vs. Python's ABC and found that in Zope you can attach interfaces to any object in Python, not just classes, and since pretty much everything in Python is an object.....
You can never have too many examples of getting stuff to work, so to illustrate the point, I give you: attaching an interface to an anonymous function.

from zope.interface import Interface, implements, directlyProvides
from zope.component import getGlobalSiteManager, adapts

class ILambdaExpression(Interface):
pass
class IConcreteInterface(Interface):
pass

class MyAdapter(object):
implements(IConcreteInterface)
adapts(ILambdaExpression)
def __init__(self, lambda_exp):
self.lambda_exp = lambda_exp
def __call__(self):
return filter(self.lambda_exp, [1,2,3,4,5,6])

gsm = getGlobalSiteManager()
gsm.registerAdapter(MyAdapter)

myFilter = lambda i : i > 3
directlyProvides(myFilter, ILambdaExpression)

result = IConcreteInterface(myFilter)()
print result

>>> [4, 5, 6]

Simple but pretty cool.