tags:

views:

288

answers:

3

I just found out python has a singleton called NotImplemented.
Why would someone want to ever return it instead of raising the NotImplementedError exception? Won't it just make it harder to find bugs, such as code that executes invalid methods?

Just wondering here...

A: 

My guess would be 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.

RichieHindle
A: 

There are functions that raise Exceptions and functions that do not, return NotImplemented could be for the latter.... it really depends on the programmer/design. That's why they are both there for use.

jcoon
+17  A: 

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.

http://jcalderone.livejournal.com/32837.html

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 !=)."

SpliFF
I would be careful using it, as this link points out near the end of the document.
jcoon