Are there 'Interfaces' in Python??

chris liechti cliechti at no.spam.gmx.net
Wed Sep 26 14:58:38 EDT 2001


t at chabry.caltech.edu (Titus Brown) wrote in
news:9ot405$3bo$1 at chabry.caltech.edu: 
>>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...

this does not require an "interface". in my opinion a cleaner atempt would 
have been if a file-like object had existed (in the standard library). 
classes that want to behave like a file could inherit from that class. 
(that class would also contain a standard implementation for readline, 
readlines, etc. so that a minimal, extending class would only need to 
provide read and write methods.

[for OO newbees: such a file like template class is a so called "abstract 
class", a class which is partly implemented but some methods are left 
unimplemented (or in python do a "raise 'not implemented'" exception)]

(this principle is used in Java's InputStream, OutputStream and others, 
which serve as base class for e.g. FileInpuStram)

my point:
some templates in the standard library would help to avoid such problems 
like mentioned above. something like "AbstractFile" would be nice.


-- 
chris <cliechti at gmx.net>




More information about the Python-list mailing list