Introduction
Within the comparisons gotcha I wrote a number of years in the past, I briefly touched on is vs ==.
Put merely,
isought to ONLY be used if you’re checking if two references confer with the identical object.
Keep in mind,iscompares object references.
Much more merely, is is not checking worth. Let’s check out a pair examples.
Gotcha
Integers
Python, particularly CPython, caches the values of -5 by 256 (inclusive). Because of this these small integer values will all the time confer with the identical object.
Notice the phrasing there – “the identical object”.
Outdoors of that vary, although, the identical just isn’t true.
>>> a = 100
>>> b = 100
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
In each of the above examples, utilizing a == b would have returned True. The error was assuming that is does the identical factor. It doesn’t.
Strings
String interning is a technique of storing just one copy of every distinct immutable string worth. Immutable strings cannot be modified. Not each string will probably be interned although. Let’s have a look:
>>> a = "Hiya"
>>> b = "Hiya"
>>> a is b
True
>>> a = "Hiya World"
>>> b = "Hiya World"
>>> a is b
False
>>> a = "Hello_World"
>>> b = "Hello_World"
>>> a is b
True
The primary and final instance interned the strings, exhibiting that a and b confer with the identical object. However, the second instance – Hiya World – did not get interned, so a and b confer with completely different objects. Why is that this?
The quick and easily reply is that any string that has solely numbers, letters or underscores will probably be interned. Since Hiya World comprises a house, it might not be interned.
The Answer
To a brand new developer that has seen tutorials that learn if a is True or if b is None, a conditional for integers or strings following the identical sample seems to be evaluating values. In the event that they check it with small, constructive numbers or easy one phrase strings, the belief holds up.
However, == is for evaluating values! Every of the above examples would return True by altering the assertion to a == b.
The few occasions that is is acceptable are if you end up checking True/False or None. In any other case, the huge majority of the time, you wish to use an equality test (==)
The Python PEP8 programming suggestions state:
Comparisons to singletons like
Noneought to all the time be executed withisorjust isn't, by no means the equality operators.
The linters within the Python ecosystem report on the utilization of is vs == too. flake8 has E711 – Comparability to None must be 'cond is None:'. ruff has the same report with it is None comparability test.
I extremely suggest a linter on your tasks to catch this, and different issues that go in opposition to finest practices.
Keep in mind, is compares object references, not object equality
