Boolean identity == True vs is True
If you want to determine whether a value is exactly True (not just a true-like value), is there any reason to use if foo == True rather than if foo is True?
If you want to make sure that foo
really is a boolean and of value True
, use the is
operator.
Otherwise, if the type of foo
implements its own __eq__()
that returns a true-ish value when comparing to True
, you might end up with an unexpected result.
As a rule of thumb, you should always use is
with the built-in constants True
, False
and None
.
Does this vary between implementations such as CPython (2.x and 3.x), Jython, PyPy, etc.?
In theory, is
will be faster than ==
since the latter must honor types' custom __eq__
implementations, while is
can directly compare object identities (e.g., memory addresses).
I don't know the source code of the various Python implementations by heart, but I assume that most of them can optimize that by using some internal flags for the existence of magic methods, so I suspect that you won't notice the speed difference in practice.
Never use is True
in combination with numpy (and derivatives such as pandas):
In[1]: import numpy as npIn[2]: a = np.array([1, 2]).any()In[4]: a is TrueOut[4]: FalseIn[5]: a == TrueOut[5]: True
This was unexpected to me as:
In[3]: aOut[3]: True
I guess the explanation is given by:
In[6]: type(a)Out[6]: numpy.bool_
is there any reason to use if foo == True rather than if foo is True?"
>>> d = True>>> d is TrueTrue>>> d = 1>>> d is TrueFalse>>> d == TrueTrue>>> d = 2>>> d == TrueFalse
Note that bool
is a subclass of int
, and that True
has the integer value 1
. To answer your question, if you want to check that some variable "is exactly True", you have to use the identity operator is
. But that's really not pythonic... May I ask what's your real use case - IOW : why do you want to make a difference between True
, 1
or any 'truth' value ?