Singleton data types such as booleans should be compared using is
and is not
rather than ==
and !=
.
You can introduce bugs in your code by doing equality checking on True
, False
and None
thanks to Python's permissive "truthy" and "falsey" checking:
This perhaps unexpected behaviour is caused by under the hood Python calling bool(value)
, which evaluates to True
for any integer other than 0
(even negative numbers).
The is
statement checks identity, while the ==
operator checks equality. Equality is for checking certain characteristics of the object have parity, while identity is for checking the objects are literally the same thing.
Under the hood, an object's equality is determined using the object's __eq__()
function. This function's purpose is to return do certain characteristics of the objects have parity.
An object's identity is determined using the id()
function. id()
returns an integer that is unique to the object for the lifetime of the object. For CPython this is the memory address of the object. Two objects cannot share the same memory location at the same time, after all.
True
, False
, and None
are singletons. Using the singleton design pattern ensures that only one object of its kind exists. This is why bool(1)
, bool(2)
, bool(True)
, bool('foo')
all return the same object. Singletons are therefore perfect for using identity checking, and doing equality checking is slightly less performant and risk introducing bugs when compared with identity checking.
If our GitHub code review bot spots this issue in your pull request it gives this advice:
1 | + | if value == False: |
Singleton data types such as booleans should be compared using is
and is not
rather than ==
and !=
.
- | if value == False: |
+ | if value is False: |
2 | + | pass |