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
OK, you've had many replies telling you why your suggestion isn't particularly worthwhile, and a few telling you how you can already do this in present-day Python.
Even if you can do it, how would you then implement a class hierarchy where the ultimate base class had virtual methods, and you wanted to derive from that class another class, to be used as a base class for usable classes, which implemented only a subset of the virtual methods, leaving the others to be implemented by the ultimate subclasses?
This use case makes your suggestion look impractical, methinks, since it requires that the programmer do what you would apparently like to specifically forbid.
regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list