NotImplemented vs NotImplementedError in Python
What is NotImplemented?
The NotImplemented is built in constant in Python. It should be used by some of the python special methods for e.g (add(), eq()) to address that the operation is not implemented but can be run by other type. If this sounds confusing let’s preview the use case of NotImplemented inside the python datetime standard library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def __add__(self, other): if isinstance(other, timedelta): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(self._days + other._days, self._seconds + other._seconds, self._microseconds + other._microseconds) return NotImplemented
The first line checks if the other object is timedelta, and if it is, it will return timedelta object that contains the time, seconds and microseconds of both objects. But if the other object is not timedelta, it doesn’t throw an exception because, maybe the other object will know how to handle this operation. So, in short words the interpreter will try the add operation on the other type. If both attempts returne NotImplemented, then the appropriate exception will be raised.
The NotImplementedError exception
This is an exception that derives from the RuntimeError. The usual use case of this exception is in the abstract class methods when they required the derived class to override them.
1 2 3 4 5 6 7 8 9 10 11 class Foo(): @property def some_method(self): raise NotImplementedError("The derived class should implement the logic.")
Also, while developing you can raise this exception as a reminder to implement this method in the future.
1 2 3 4 5 6 7 8 9 10 11 class Foo(): #TODO def new_method(self): raise NotImplementedError("Still not implemented.")