Are there 'Interfaces' in Python??

Titus Brown t at chabry.caltech.edu
Wed Sep 26 13:41:25 EDT 2001


In article <dqvso9.rgl.ln at 10.0.0.1>, Carl Banks  <idot at vt.edu> wrote:
>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.

I'm not clear why this is such a GOOD thing.  It's not necessarily BAD,
unless you (for example) have to debug the 'rfc822' module, which assumes
that any file-like object which has 'seek' must have 'tell', but doesn't
indicate in any way what the lack of both affects handling, and furthermore
raises an error if you have one but not the other.

There's also the mystifying lack of 'readlines' on StringIO objects
in Python before 2.0.  Does a file-object-like-thing have to have
readlines?  Well, they all do now -- how about seek? tell? read() behavior?
You tell me, after going and looking at all the file-object-like-things
in the distribution.  Oh -- but wait, you can't find them all, because
they're all unrelated...

I would rather regard this as neutral & a convenience for people writing
code that uses file-object-like-things.  It's certainly not a convenience
for people writing new classes that attempt to emulate the behavior of
already-existing objects with unclear definitions, and it sure would be
nice to have the option of some type checking built into the language,
but I understand why it's not there and appreciate the convenience.  But
there are downsides too...

cheers,
--titus



More information about the Python-list mailing list