I write this post in English because I assume that anyone that is in need of using its content most likely read it, my apologies if not.
Yesterday I found myself in a place I have been before, in the need of implementing interfaces pattern, my first reaction was, hey zope already has this, but then I remembered that we (the guys at Ninja-Ide </shameless plug>) did not want to add dependencies, especially not zope ones, so I tried to emulate interface behaviour, here is my first approach.
class MethodNotImplemented(Exception):
pass
def implements(iface):
"""
A decorator to check if interfaces are correctly implmented
#TODO: check if functions parameters are correct
"""
def implementsIA(cls, *args, **kwargs):
"""
Find out which methods should be and are not in the implementation
of the interface, raise errors if class is not correctly implementing.
"""
should_implement = set(dir(iface)).difference(set(dir(object)))
should_implement = set(should for should in should_implement if
not should.startswith("_"))
not_implemented = should_implement.difference(set(dir(cls)))
if len(not_implemented) > 0:
raise MethodNotImplemented("Methods %s not implemented" %
", ".join(not_implemented))
if cls.__name__ not in globals():
#if decorated a class is not in globals
globals()[cls.__name__] = cls
return cls
return implementsIA
The typical usage is:
class IExample(object):
def amethod(self):
pass
@implements(IExample)
class Example(object):
...
Now, this will fail on import raising the MethodNotImplemented exception unless Example has all the same methods (that is public methods) than IExample, I would like this to also check if the method accepts at least the same parameters, but it is a work in progress.


