This exception is derived from :exc:`RuntimeError`. In user defined base
classes, abstract methods should raise this exception when they require
derived classes to override the method, or while the class is being
developed to indicate that the real implementation still needs to be added.
If "abstract base classes" are meant to mean ABCs from the standard library, this is unnecessary as the ABC metaclass will prohibit instantiation of any derived class that doesn't implement an abstract method. Indeed, adding a raise would be dead code that would flaunt, say, coverage metrics.
The text was updated successfully, but these errors were encountered:
I think the purpose of raising NotImplementedError is to protect against calling the abstract method from the class like this:
>>> from abc import ABC, abstractmethod
>>>
>>> class Animal(ABC):
... @abstractmethod
... def move(self):
... raise NotImplementedError
...
>>> class Human(Animal):
... def move(self):
... print("human move")
...
>>> Animal.move(Human())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in move
NotImplementedError
If we removed the NotImplementedError, calling the abstract move method would silently do nothing.
I think the statement should stay, or even be made more prominent in the docs. I see lots of abstract methods which wrongly (in my opinion) just have pass as the body.
Xophmeister commentedDec 21, 2022
Documentation
In the documentation for
NotImplementedError
, we see the following:cpython/Doc/library/exceptions.rst
Lines 299 to 304 in a7715cc
If "abstract base classes" are meant to mean ABCs from the standard library, this is unnecessary as the ABC metaclass will prohibit instantiation of any derived class that doesn't implement an abstract method. Indeed, adding a
raise
would be dead code that would flaunt, say, coverage metrics.The text was updated successfully, but these errors were encountered: