A simple decorator that helps define abstract methods: when such a method is called, an appropriate exception is raised.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32  | def abstractmethod(method):
    def default_abstract_method(*args, **kwargs):
        raise NotImplementedError('call to abstract method ' + repr(method))
    default_abstract_method.__name__ = method.__name__
    
    return default_abstract_method
if __name__ == '__main__':
    class A:
        @abstractmethod
        def foo(self, data): pass
    class B(A):
        def foo(self, data):
            self.data = data
    a = A()
    b = B()
    b.foo(5)
    
    exception_raised = False
    try:
        a.foo(3)
    except NotImplementedError:
        exception_raised = True
    assert exception_raised
    print 'OK'
 | 
I find it more consistent that the (nonetheless elegant): def foo(self): abstract
Download
Copy to clipboard
Why not raise built-in NotImplementedError?
Good idea, didn't know about that.
The only drawback to this approach is you won't fail withTypeError for incorrect arguments being passed.