Enumeration idioms: Values from different enumerations

Bengt Richter bokr at oz.net
Tue Dec 20 09:37:04 EST 2005


On Tue, 20 Dec 2005 09:16:03 +1100, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:

>eswald at gmail.com writes:
>> Ben Finney wrote:
>>> Is there some behaviour other than "evaluate to False" or "raise an
>>> exception", that could indicate "not comparable"?
>>
>> Yes: return NotImplemented.  Note that the == operator automagically
>> returns False in this case.
>>
>>     >>> "spam".__eq__("spam")
>>     True
>>     >>> "spam".__eq__("ham")
>>     False
>>     >>> "spam".__eq__(23)
>>     NotImplemented
>>
>> This way, the user could explicitly call __eq__ and check for
>> NotImplemented if he desires the exceptional behavior.
>
>Thanks, I was unaware of the standard usage of NotImplemented. That
>seems like a sensible solution.
>
>    <URL:http://docs.python.org/ref/types.html#l2h-29>
>
OTOH, that says the truth value is True, so this does not fail:

 >>> assert 'spam'.__eq__(23)
 >>>

Which seems counterintuitive. The explicit value test

 >>> assert 'spam'.__eq__(23) is NotImplemented

would succeed irrespective of truth value,
but it seems contorted and unpythonic to have to write

 >>> assert 'spam'.__eq__(23) is False
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 AssertionError
 >>>

to get the effect you might naively expect from

 >>> assert 'spam'.__eq__(23)


I wonder what the rationale for the NotImplemented True truth value was, as opposed to False.

On the third hand, I recently posted an idea of using NotImplemented
as a (handy because predefined) logically true sentinel value to return
from a test function to distinguish not_applicable from applicable_and_ok
when desired, yet allowing assert testfun(...) to succeed either way.
That code would have to use another boolishly True sentinel if NotImplemented
were changed to have False truth value.

Maybe it would be useful to have a couple of builtin sentinels like TrueSentinel
and FalseSentinel (or sentinel_t and sentinel_f or pick some names ;-) so we
wouldn't be tempted to misuse unique builtins like NotImplemented and Exception etc.

Regards,
Bengt Richter



More information about the Python-list mailing list