Pythonic Abstract Base Class / Interface

KefX keflimarcusx at aol.comNOSPAM
Tue Oct 28 09:33:27 EST 2003


>So, as I see it I could:
>a) create a base class with stubs for all the interface and derive from that.
>b) create an empty base class and derive from that.
>c) just make the concrete classes directly with no inheritance commonality.

It's funny, I was actually thinking about the same thing not long before this
got posted.

Being a newcomer of sorts to Python, I can't really comment on what's
"Pythonic" or not as well as others can (and only Guido knows for sure), but I
can make some guesses. Pythonic in my mind is clear, concise, but flexible.
This is a case where you can't get all of them at the same time. The most
concise, of course, is answer C, at the possible expense of clarity and
flexibility. Clarity may be more important to you, and the winner for that is
A. (Somebody else suggested using docstrings in the stubs; I second that
opinion.) However, A is less concise.

A and B are both flexible, because you can implement more functions in the base
class, and poof! Derived classes gain the benefits right then and there. But of
course you have to make sure you don't break any of them (if you're careful and
you know what classes are derived from it, and I'm guessing you do, it
shouldn't be a problem). I'm inclined to say that B is more flexible than A,
because if you remove a stub function and some code somewhere relies on it
being called (whether or not it's a no-op), then a derived class that doesn't
define it will be broken. Of course, in practice, this isn't too likely...

To summarize:
C is concise and nothing else
B is concise (not quite as much as C), somewhat clear, flexible
A is clear, flexible (not quite as much as B), but not concise

I'm inclined to pick A, since I'm a bit of a clarity freak, but I don't really
feel that any one of these is more Pythonic than another on its own merits...it
kind of depends on the situation. If subclasses are likely to be small, I would
probably pick C or at most B and save some effort...if subclasses are likely to
be a significant size, I'd definitely pick A.

- Kef





More information about the Python-list mailing list