Should `bool(NotImplemented)` become an error?

The documentation for NotImplemented says:

Changed in version 3.9: Evaluating NotImplemented in a boolean context is deprecated. While it currently evaluates as true, it will emit a DeprecationWarning. It will raise a TypeError in a future version of Python.

And indeed that’s what happens at runtime:

% ./python.exe -c 'bool(NotImplemented)'
<string>:1: DeprecationWarning: NotImplemented should not be used in a boolean context

This warning was introduced in Python 3.9 (PR, issue), four years ago. That seems like enough time to consider whether we want to go through with this deprecation.

Personally I don’t have a strong opinion, except that I don’t want the documentation to claim that something will happen when it isn’t happening. I’ll summarize the arguments for and against that show up in the issue.

Arguments in favor of making bool(NotImplemented) raise:

  • Calling bool() on NotImplemented frequently indicates a bug, such as calling not self.__eq__(other).

Arguments against:

  • All other Python builtins are usable in a boolean context. NotImplemented would be the exception.
  • Some (possibly questionable) coding patterns start raising errors, such as list(filter(None.__ne__, L)) to filter None out of a list.
4 Likes

Well, the reason for the deprecation is unique to NotImplemented (see original issue). So I don’t buy the first “Argument against” as a strong argument (there is such a thing as being too consistent). The second bullet already shows a warning, so IMO it’s fair game.

So I’m still in favor to go through with it.

7 Likes

Thanks, it sounds like we should go forward with the deprecation.

I think we should wait until after 3.14 development starts, though; it’s good for this sort of change to go in right in the beginning of the alpha phase, not at the very end.

6 Likes

I just put up a PR implementing this: gh-118767: Make bool(NotImplemented) raise TypeError by JelleZijlstra · Pull Request #118775 · python/cpython · GitHub.