[Python-ideas] Programming recommendations (PEP 8) and boolean values

Alexander Belopolsky alexander.belopolsky at gmail.com
Thu Aug 9 00:37:15 CEST 2012

On Wed, Aug 8, 2012 at 10:11 AM, Michael Foord <fuzzyman at gmail.com> wrote:
> True and False are singletons, so if you want to check precisely for True
> and False then an identity check seems appropriate.

Technically speaking, True and False are not singletons - they are
each an instance of the bool class and a singleton is the *only*
instance of a class.   I am not sure what the right term is for bool
instances behavior, but the key feature here is that if x is known to
be bool, x == True is equivalent to x is True.  This property is not
unique to bool an singletons like None.  For example, in CPython if x
is an int, x == 0 is equivalent to x is 0 because a few small integers
are preallocated.  However, in the case of int, this property is
clearly an implementation detail and alternative implementations
should be free to vary the number of preallocated integers or not
preallocate at all.

With respect to bool, an argument can be made that it having only two
preallocated instances is a language feature rather than an
implementation detail and user can rely on the fact that True, bool(1)
and say not [] all return the same instance.  If this is so, I think
this fact should be mentioned somewhere, but probably not in PEP 8.

More information about the Python-ideas mailing list