[Tutor] Interfaces in Python

Kent Johnson kent37 at tds.net
Wed Jun 14 14:16:59 CEST 2006


Emily Fortuna wrote:
> Hi friends,
> I am learning Python and relating to my knowledge of Java... What is (Is 
> there?) the equivalent of Java interfaces in Python?  How could I write 
> my own?

Explicit, formal interfaces are used much less frequently in Python than 
in Java, and for beginners they are not needed at all. In Python, 
interfaces are often implicit and defined only by usage and 
documentation. Sometimes the usage is called a protocol. Because Python 
is dynamic, there is not need to declare the type of an object, you just 
use it in the desired way. This is called "duck typing".
http://c2.com/cgi/wiki?DuckTyping

For example, the Python docs often talk about a "file-like object". A 
file-like object is any object that implements enough of the file 
protocol to act like a file. In some contexts, it might be enough to 
implement a read() method; in other contexts, the full file protocol 
might be needed. The StringIO module contains a class that implements a 
file-like wrapper around a memory buffer. An instance of StringIO can be 
passed to any function that expects an open file. StringIO doesn't 
inherit from any interface, it just implements the needed functions.

Large Python projects seem to need something more formal than this. I 
think Zope, Twisted and PEAK have all invented ways to formalize this 
notion, and one of them may become part of Python in the future. But for 
small projects, duck typing and implicit protocols work pretty well.

I hope someone else will explain this better than me...

Kent



More information about the Tutor mailing list