Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Exception for notifying that subclass should implement a method?

Suppose I want to create an abstract class in Python with some methods to be implemented by subclasses, for example:

class Base():
    def f(self):
        print "Hello."
        self.g()
        print "Bye!" 

class A(Base):
    def g(self):
        print "I am A"

class B(Base):
    def g(self):
        print "I am B"

I'd like that if the base class is instantiated and its f() method called, when self.g() is called, that throws an exception telling you that a subclass should have implemented method g().

What's the usual thing to do here? Should I raise a NotImplementedError? or is there a more specific way of doing it?

like image 974
Manuel Araoz Avatar asked Aug 13 '10 03:08

Manuel Araoz


1 Answers

In Python 2.6 and better, you can use the abc module to make Base an "actually" abstract base class:

import abc

class Base:
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def g(self):
        pass
    def f(self): # &c

this guarantees that Base cannot be instantiated -- and neither can any subclass which fails to override g -- while meeting @Aaron's target of allowing subclasses to use super in their g implementations. Overall, a much better solution than what we used to have in Python 2.5 and earlier!

Side note: having Base inherit from object would be redundant, because the metaclass needs to be set explicitly anyway.

like image 103
Alex Martelli Avatar answered Oct 13 '22 01:10

Alex Martelli