How about "pure virtual methods"?

Jp Calderone exarkun at
Sun Dec 19 01:13:21 CET 2004

On Sun, 19 Dec 2004 01:49:50 +0200, Noam Raphael <noamr at> wrote:
> 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.

  What about the mechanism you described below?  That can be implemented 
without any changes to the Python language or additions to the standard 
library, and does just what you want.

> 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".

    def foobar(x, y, z):
        raise NotImplementedError("Subclasses must implement this")

> 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(
> ======================
> then if I try to instantiate BaseClass I would get an exception, but 
> instantiating RealClass will be ok.
> Well, what do you say?

  It seems as though this is more in the realm of PyChecker and unit 
tests than desirable language features.  PyChecker will already point 
out when a method cannot do anything but raise an exception, as a "pure 
virtual function" does.  Unit tests, similarly, will show you where you 
forgot to implement a method, because they _will_ exercise your code.

  Nothing is preventing you from creating a base class and a 
notimplemented decorator which cooperative to make subclasses 
uninstantiable if "pure virtual methods" remain, though.


More information about the Python-list mailing list