Are there 'Interfaces' in Python??

Carl Banks idot at vt.edu
Wed Sep 26 12:30:05 EDT 2001


tszeto <tszeto at mindspring.com> wrote:
> Hello,
> 
> Was wondering if Python supported 'Interfaces' (something akin to Java
> interfaces)? Or if there's a workaround to get the same thing.

IMHO, ***THE*** best thing about Python is that inheritance and
interfaces and other such tricks are not required to get polymorphic
behavior.

Take, for example, StringIO objects.  They are not syntactically
related to File objects in any way: neither is derived from the other,
they are not derived from a common base class, and they do not
implement a common "official" interface.  Yet, because StringIO
objects provide the same methods that File objects provide, one can
use StringIO object as if they were an ordinary File objects.

Basically, if something looks like a File object, and acts like a File
object, one can use it like a File object.  So, unlike Java, you don't
need interfaces to get polymorphic behavior in Python.


Now, if you want intefaces so as to catch errors when your classes
fail to implement required methods, Python doesn't have anything like
that.  But you can define a function that explicitly checks whether
the class has the methods you require:

    def assert_provides_interface (klass):
        assert has_attr (klass, 'methodX')
        assert type(klass.methodX) == MethodType
        ...

    class Y:
	def methodX ():
            ...

    assert_provides_interface (Y)


This is a simple example; there's probably thousands of ways to
improve it.


-- 
CARL BANKS




More information about the Python-list mailing list