Welcome, guest | Sign In | My Account | Store | Cart

A simple decorator that helps define abstract methods: when such a method is called, an appropriate exception is raised.

Python, 32 lines
 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

3 comments

pavel 10 years, 7 months ago  # | flag

Why not raise built-in NotImplementedError?

jimmy2times (author) 10 years, 7 months ago  # | flag

Good idea, didn't know about that.

Peter Ruibal 10 years, 7 months ago  # | flag

The only drawback to this approach is you won't fail withTypeError for incorrect arguments being passed.

Created by jimmy2times on Tue, 19 Apr 2011 (MIT)
Python recipes (4591)
jimmy2times's recipes (4)

Required Modules

  • (none specified)

Other Information and Tasks