PEP 245: Python interfaces

Alex Martelli aleaxit at yahoo.com
Fri Mar 23 18:42:14 EST 2001


"Clark C. Evans" <cce at clarkevans.com> wrote in message
news:mailman.985380515.28565.python-list at python.org...
    [snip]
> you may have an interface with four functions.  The implementation
> of three functions may be completely optional or trivial.  With
> the class approach, you could label the one critical method as
> "pure" and then provide a reasonable, default implementation
> for the other methods.
>
> > Classes could in some way, be extened to have an inline "interface"
> > but that is mixing your interface with your implementation.
>
> I'm not convinced that they are entirely seperate ideas.

I used to suspect this was just a C++ distortion, but after
seeing the way Haskell does typeclasses I'm now convinced
otherwise.  A Haskell typeclass need not have any 'pure'
method -- they may ALL be implemented in terms of each
other (unbounded recursion!), a type that instances that
typeclass just needs to override a minimal set of methods
to ensure no unbounded recursion occurs.  And meanwhile,
as well as providing convenience, the mutually recursive
definitions in the typeclass specify the semantics!

Example: consider a typeclass modeling a subset of what
fileobject does today, specifically write and writelines.
Each may be defined in terms of the other (pythonic-ish
syntax for the Haskell typeclass idea!-):

typeclass writeablefile:
    def write(self, astring):
        self.writelines([astring])
    def writelines(self, stringslist):
        for astring in stringslist:
            self.write(astring)

See?  Neither needs to be defined as 'primary' -- they
are two methods of equal dignity, EITHER may be overridden
by a type instancing writeablefile and the other will be
picked up through its semantic definition in the
typeclass.  Now is this cool, or what?!-)

(Of course, BOTH may be overridden, e.g. for efficiency,
but at least the definitions in the typeclass stand as
good documentation of the intended semantics!-).


> > How can you reuse that?
>
> Just like you use classes today... look at the PyXML stuff,
> specifically the Sax interfaces.  Providing a default, or
> trivial implemenation for optional methods is a common
> technique in C++ and very valueable.
>
> In Java you are forced to have two constructs, an interface,
> and then a "base handler".  Having the interfae and the
> base implementation in two places just makes more places
> where errors can pop-up.

I disagree on this -- I like the interface/basehandler
separation so much that I tend to write C++ that way,
too (via mixins, generally, and templates too -- Java
doesn't have those, so more manual boilerplate is
needed -- but that's a SMOP).


Alex






More information about the Python-list mailing list