Missing interfaces in Python...

Kay Schluehr kay.schluehr at gmx.net
Wed Apr 19 03:09:06 EDT 2006


redefined.horizons at gmail.com wrote:
> I'm coming from a Java background, so please don't stone me...
>
> I see that Python is missing "interfaces". The concept of an interface
> is a key to good programming design in Java, but I've read that they
> aren't really necessary in Python. I am wondering what technique I can
> use in Python to get the same benefits to a program design that I would
> get with interfaces in Java.
>
> For example, if I want to have a program with a Car object, and a Bus
> object. I want both of these objects to present a common group of
> methods that can be used by Mechanic objects, but slightly different
> methods that can be used by Driver objects.
>
> In Java I would accomplish this by defining an IFixable interface that
> would be implemented by both the Car and Bus objects. Mechanic objects
> would work with any object implementing this interface.
>
> How would I approach this problem in Python? I think I would use an
> abstract class instead of an interface for IFixable, since Python
> supports multiple inheritance, but I'm not sure this is correct.
>
> Thanks for any suggestions.
>
> Scott Huey

The answer is called "duck typing" or "structural typing". Any two
classes that implement a set of methods with pairwise equal signatures
can be considered as "presenting a group of methods". You do not have
to create a special construct and assign it to classes ( e.g. via an
"implements" directive ) in order to make it work. That's because you
are not enforced to know the type of an object at compile time. Car and
Bus classes may be selected from two completely different libraries
without any common convention but it is still possible ( though not
very likely without any adaption ) that they work together and show
sound behaviour ( you have to prove at least certain behavioural
properties using unit tests ).

"Duck typing" is also the reason why coupling of an interface with an
implementation is not harmfull in Python. You won't find many deep
class hierarchies and extensive frameworks. This has the advantage that
a classification you have done once at the beginning of your project in
the design phase is not considered to be carved in stone.
In Java/C#/C++ you can achieve many of the same effects of using
"generic" or "templates" but if you are not start coding with them from
the very beginning you loose many of their benfits. In Python this is a
non-issue.




More information about the Python-list mailing list