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

Carl Banks pavlovevidence at gmail.com
Fri Jan 5 06:28:27 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?

You can't (easily).

If your subclass doesn't override a method, then you'll get a big fat
AttributeError when someone tries to call it.  But this doesn't stop
someone from defining a subclass that fails to override the method.
Only when it's called will the error show up.  You can, as others have
noted, define a method that raises NotImplementedError.  But this still
doesn't stop someone from defining a subclass that fails to override
the method.  The error still only occurs when the method is called.

There are some advantages to using NotImplementedError:

1. It documents the fact that a method needs to be overridden
2. It lets tools such as pylint know that this is an abstract method
3. It results in a more informative error message

But, in the end, if someone wants to define a class that defiantly
refuses to declare a method, you can't stop them.


Carl Banks




More information about the Python-list mailing list