[Python-Dev] PEP 246 - Object Adaptation

Alex Martelli aleax@aleax.it
Mon, 15 Jul 2002 21:20:25 +0200


On Monday 15 July 2002 04:04 pm, Guido van Rossum wrote:
> (Changing the subject)
>
> > The big question is rather: given that Isub inherits from Isuper,
> > does any object implementing Isub also implicitly implement Isuper?
>
> This probably shows my naivete more than anything else...
>
> I'd say "of course", based on an example where Isuper is
> FileOpenForReading and Isub is FileOpenForReadingAndWriting.
> It would be strange if a file open for reading and writing was not
> acceptable in a place where a file open for reading is accepted
> (because it implements all the right methods).  Or is the fact that it
> implements *more* the problem?

It often does look like a R/W container "implements more" than
the corresponding R/O container, but in many cases the R/W
"subclass" can guarantee fewer invariants -- and they're often
invariants quite hard to express even in languages that do
support contracts.  To see that in the case of a file, imagine
the file interface having a rewind method.  With a R/O file, I
know that:

def firstbyte(f):
    f.rewind()
    return f.read(1)

always returns the same byte for a given f.  If f is R/W, then I
can't be certain any more, which may change the caching
strategy I need to use, for example.

(Of course, the same uncertainty might be present if, while
f is R/O, the OS/whatever also allows other processes to
open the underlying file for R/W at the same time, so in the
case of files this only goes so far).

More generally, it's _nice_ to be able to use inheritance just
for implementation purposes, without necessarily having to
worry about IS-A.  When i have two interfaces with, say,
three methods in common, I can refactor those three methods
up to a common base-interface -- even if no object actually
deigns to supply that base-interface.  This simply avoids a
little nasty copy-and-paste coding -- not an earth-shaking
concern, admittedly.  But, still, nice.


Alex