Program to an interface, not an implementation

Daniel Dittmar daniel.dittmar at sap.com
Mon Jun 10 08:45:35 EDT 2002


Egbert Bouwman wrote:
> This I read as:
> For Python interface_inheritance does not require class_inheritance.
>
> So you can inherit an interface without inheriting the class,
> but interface_inheritance by way of class_inheritance is possible as
> well. That means at least two things:
> - python has interface inheritance (which some people deny),
> - interface_inheritance without class_inheritance is a kind of
> cultural   (not genetical) inheritance: give it the same name and all
> is well.   But for me that is only polymorphism !

Perhaps it would be better to skip the term interface_inheritance
altogether. In Javaspeak, you IMPLEMENT an interface, you promise that you
conform to a specification. In Java, this can be checked at compile time. In
Python, you could probably create interface objects which can check if a
given object or class implements all the methods that are required.

It is only polymorphism in the way the language runtime handles this. But it
is a difference in the way you document your software.

> I do all this hair splitting because the GoF say (still page 17)
> that many patterns depend on the distinction between interface- and
> implementation inheritance. How do you define in python the
> interface inheritance the GoF talk about ?

An example from the module pickle:
  dump(object, file[, bin])
  ...
  file must have a write() method that accepts a single string argument. It
can thus be a file object opened for writing, a StringIO object, or any
other custom object that meets this interface.


You specify the methods that will be called. Having a well known object with
the required behaviour is always helpful.

The important part about 'programming to an interface' is this: If you're
implementing the 'dump' method, don't call arbitrary methods of a file
object just because you happen to test it with a file object.

Daniel





More information about the Python-list mailing list