abyx abyx -5 years ago 180
Python Question

Why return NotImplemented instead of raising NotImplementedError

Python has a singleton called


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

Answer Source

It's because __lt__() and related comparison methods is 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 !=)."

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download