Wednesday, October 20, 2004

Python Interfaces

Ned Batchelder had problems mimicking Java's interfaces in Python and then he also had problems departing from that too.

The problem is that the implementer actually implements all the methods in the interfaces (via inheritance) regardless of whether it overwrites the behavior or not.

If there were real interfaces in Python's language, then this would not be a problem since it would only be implemented if it actually implements it.

He also explains how one does this in Java, which IMO is because Java forces you to implement all the methods in the implementer, so you must start creating hierarchies of interfaces to allow the implementer implement only one method, namely the child interfaces's method.

In python, thanks to the fact that everything is an object and dynamic nature of things you can declare that something does something other ways:
methodName.notYetImplemented = True even if there is code in the body of the method and then rely on this attribute of the method's object rather then on the fact that there is code in the body of the method or not like in Java.


def makeAbstract(f):
f.abstract=True
return f

class NotImplemented(Exception): pass

class Executable:
@makeAbstract
def oneWay(self):
raise NotImplemented
@makeAbstract
def secondWay(self):
raise NotImplemented
or for py2.3
oneWay = makeAbstract(oneWay)
secondWay = makeAbstract(secondWay)

class Statement(Executable):
def oneWay(self):
print "one way executed"

s = Statement()

if not hasattr(getattr(s, 'oneWay'), "abstract"):
s.oneWay()
else:
s.secondWay()

Of course someone can argue how much more readeble an interface inheritace dispach mechanism is vs a switch dispache mechanism such like the one above, and I agree that often that is true, however there are many instances when "simple is simpler and therefore better". However this discution dosen't interests me and I let the purists take onto that.
Now if you would like to let the dispach mechanism be taken care of by someone else, not you, then better use something like "runtime object providing a protocol"PyProtocols wich is now also arguable as clean or cleaner then a "compile time object following interface specifications" such as Java's.

0 Comments:

Post a Comment

<< Home