What is proper way to require a method to be overridden?

Patrick Down patrick.down at gmail.com
Sat Jan 6 00:57:14 CET 2007


jeremito wrote:
> I am writing a class that is intended to be subclassed.  What is the
> proper way to indicate that a sub class must override a method?
>
> Thanks,
> Jeremy

Decorators to the rescue?

def must_override(f):
    def t(*args):
        raise NotImplementedError("You must override " + f.__name__)
    return t

class Foo:
    @must_override
    def Bar(x,y): pass

Foo().Bar()

Traceback (most recent call last):
  File "testit.py", line 14, in ?
    Foo().Bar()
  File "testit.py", line 5, in t
    raise NotImplementedError("You must override " + f.__name__)
NotImplementedError: You must override Bar




More information about the Python-list mailing list