I think there is no particularly good reason to prohibit subclassing bool
.
Guido said (as quoted in the top-voted, accepted answer) that it preserves the invariant that True
and False
are the only instances of bool
. But that is not true:
>>> class BOOL:
... @property
... def __class__(self):
... return bool
...
>>> FileNotFound = BOOL()
>>> isinstance(FileNotFound, bool)
True
>>>
This behavior of __class__
is documented and used in the standard library.
I guess you could argue that the prohibition on subclassing still preserves some kind of "moral" closedness of bool
, but it's not clear to me what good that is. Reading Guido's rationale, a reasonable Python programmer would conclude he's saying that isinstance(x, bool)
is a safe equivalent of x is True or x is False
, which it isn't.
Furthermore, if the exact type matters to you, you should be testing type(x) is T
, not isinstance(x, T)
, in any case. Making those expressions equivalent in the one case of bool
—even if they succeeded in doing it—would just encourage the writing of code that doesn't clearly express intent, in that one case.
(type(FileNotFound)
is BOOL
, not bool
, so the exact-type test does work here. A malicious actor could, I suppose, replace type
. Generally, expecting any sort of invariant to hold in Python is a fool's errand.)