[Tutor] intefaces in python

Alan Gauld alan.gauld at btinternet.com
Sun Jun 28 19:48:15 CEST 2009


"Amit Sethi" <amit.pureenergy at gmail.com> wrote 

> Hi , I don't suppose python has a concept of interfaces. 

Yes and No, I'll come back to that...

> But can somebody tell me if their is a way i can  implement 
> something like a java interface in python.

First, can you tell me why you would want to?
Java style interfaces tend to make your code much less 
reusable and much less flexible if you are using a dynamically 
typed language. There are very few real advantages to them
over defining, say, a mixin or using multiple inheritance (which 
of course Java can't do)

The normal way of defining a Java style Python interface 
class is simply to define a class that has a set of methods
thaty either do or return nothing or raise some kind of 
NotImplementedError exception. But usually providing 
a mixin is a much more powerful style of programming 
in Python since you can provide partial implementations 
of the methods or generic methods that are not dependant 
on the types of the parameters.

Coming back to the original question, Python has a very 
strong concept of an interface, that is how it checks types, 
if an interface does not exist it will raise a TypeError. But it 
does it at runtime and it does it at the method level not the 
class level. Very different to Microsoft's concept which was 
designed to meet the needs of COM and was subsequently 
adopted by Java.

There has also been talk of introducing syntax to create interfaces 
into Python which I personally think is a very, very poor idea! 
But quite a lot of what I think are poor ideas get intro Python 
so that doesn't mean much! :-)

Alan G.



More information about the Tutor mailing list