How about "pure virtual methods"?

Noam Raphael noamr at remove.the.dot.myrea.lbox.com
Sun Dec 19 00:49:50 CET 2004


Hello,

I thought about a new Python feature. Please tell me what you think 
about it.

Say you want to write a base class with some unimplemented methods, that 
subclasses must implement (or maybe even just declare an interface, with 
no methods implemented). Right now, you don't really have a way to do 
it. You can leave the methods with a "pass", or raise a 
NotImplementedError, but even in the best solution that I know of, 
there's now way to check if a subclass has implemented all the required 
methods without running it and testing if it works. Another problem with 
the existing solutions is that raising NotImplementedError usually means 
"This method might be implemented some time", and not "you must 
implement this method when you subclass me".

What I suggest is a new class, called notimplemented (you may suggest a 
better name). It would get a function in its constructor, and would just 
save a reference to it. The trick is that when a new type (a subclass of 
the default type object) is created, It will go over all its members and 
check to see if any of them is a notimplemented instance. If that is the 
case, it would not allow an instantiation of itself.

What I want is that if I have this module:

======================

class BaseClass(object):
     def __init__(self):
         ...

     @notimplemented
     def save_data(self, filename):
         """This method should save the internal state of the class to
         a file named filename.
         """
         pass

class RealClass(BaseClass):
     def save_data(self, filename):
         open(filename).write(self.data)

======================

then if I try to instantiate BaseClass I would get an exception, but 
instantiating RealClass will be ok.


Well, what do you say?

Noam Raphael



More information about the Python-list mailing list