Singleton data types such as booleans should be compared using
is not rather than
You can introduce bugs in your code by doing equality checking on
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).
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() 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.
None are singletons. Using the singleton design pattern ensures that only one object of its kind exists. This is why
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:
Code Review Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code
singleton-equality-checking in your pyproject.toml file.