python – Why return NotImplemented instead of raising NotImplementedError

The Question :

318 people think this question is useful

Python has a singleton called NotImplemented.

Why would someone want to ever return NotImplemented instead of raising the NotImplementedError exception? Won’t it just make it harder to find bugs, such as code that executes invalid methods?

The Question Comments :

The Answer 1

306 people think this answer is useful

It’s because __lt__() and related comparison methods are quite commonly used indirectly in list sorts and such. Sometimes the algorithm will choose to try another way or pick a default winner. Raising an exception would break out of the sort unless caught, whereas NotImplemented doesn’t get raised and can be used in further tests.

To summarise that link:

NotImplemented signals to the runtime that it should ask someone else to satisfy the operation. In the expression a == b, if a.__eq__(b) returns NotImplemented, then Python tries b.__eq__(a). If b knows enough to return True or False, then the expression can succeed. If it doesn’t, then the runtime will fall back to the built-in behavior (which is based on identity for == and !=).”

The Answer 2

137 people think this answer is useful

Because they have different use cases.

Quoting the docs (Python 3.6):


should be returned by the binary special methods (e.g. __eq__(),
__lt__(), __add__(), __rsub__(), etc.) to indicate that the operation is not implemented with respect to the other type

exception NotImplementedError

[…] 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.

See the links for details.

The Answer 3

16 people think this answer is useful

One reason is performance. In a situation like rich comparisons, where you could be doing lots of operations in a short time, setting up and handling lots of exceptions could take a lot longer than simply returning a NotImplemented value.

The Answer 4

5 people think this answer is useful

Returning NotImplemented by a function is something like declaring that the function is unable to process the inputs but instead of raising exception, the control is transferred to another function known as Reflection Function with a hope that the Reflection Function might be able to process the inputs.

Firstly, the Reflection Functions associated with any functions are predefined. Secondly when the original function returns NotImplemented, interpreter runs the Reflection Function but on the flipped order of input arguments.

You can find detailed examples here

Add a Comment