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

sjdevnull at yahoo.com sjdevnull at yahoo.com
Fri Jan 5 23:57:40 EST 2007


Patrick Down wrote:
> 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

I'd think twice before using a decorator.  This just seems less clear
to read than simply raising NotImplementedError, and the traceback
points into the decorator instead of the function that you really care
about.




More information about the Python-list mailing list