Pythonic Abstract Base Class / Interface

Eric Brunel eric.brunel at pragmadev.N0SP4M.com
Tue Oct 28 09:32:55 EST 2003


Michael Hudson wrote:
> Tom Evans <tom_evans_a at uk.co.yahoo.reverse> writes:
> 
> 
>>My basic question:
>>If I have a specific interface which I know is going to be implemented 
>>by a number of classes, but there is no implementation commonality 
>>between them, what is the preferred form for this in Python?
> 
> [...]
> 
>>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.
>>
>>Is there a clear pythonic way, or does it depend a bit more on the 
>>design of the specific program?
> 
> 
> I'd say c) was probably the most pythonic, but it depends a bit.  a)
> might have some documentation value -- for instance, you could
> document required relations between the methods in their docstrings.

Another argument in favor of a) is that pychecker has an option to check if 
methods only raising exceptions in a super-class are actually implemented in all 
its sub-classes. So:

class MyInterface:
   def spam(self):
     raise NotImplementedError
class MyClass(MyInterface):
   ...

has actually more than a documentation value: pychecker should at least report a 
warning if the method spam is not defined in MyClass.

HTH
-- 
- Eric Brunel <eric dot brunel at pragmadev dot com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com





More information about the Python-list mailing list