May-12-2020, 09:40 PM
It compares the object ID which is the memory location of the object.
In earlier versions of Python you could do nasty things like change the value of True and False. Nobody raised a peep if you wrote:
"is" is slightly more efficient. When testing "x == True" we need to call __eq__(x, True which has to get the value in x and the value in True and do a comparison. When using "x is True" we can directly compare the object ID's.
"Comparisons to singletons like None should always be done with is or is not, never the equality operators."
"never" is a bad word. Many small integers are singletons. I don't remember the exact range, some integers are singletons:
But the message in that message is a good one. When you can use it, "is" is a better test than "==", and both are bar better than the implicit test in "if x:" If "x" what? If x != 0 and x != None and x != False?
In earlier versions of Python you could do nasty things like change the value of True and False. Nobody raised a peep if you wrote:
x = True True = 1 if x != True: print x, '!=', TrueHowever if you wrote his code using is
x = True True = 1 if x is not True: print(x, '!=', True)The output of the first example is indeterminant. Maybe True was set to 1. The second example never prints because no matter what value we assign True, it always "is" True. It is comforting to write code that cannot be broken.
"is" is slightly more efficient. When testing "x == True" we need to call __eq__(x, True which has to get the value in x and the value in True and do a comparison. When using "x is True" we can directly compare the object ID's.
"Comparisons to singletons like None should always be done with is or is not, never the equality operators."
"never" is a bad word. Many small integers are singletons. I don't remember the exact range, some integers are singletons:
x = 1 print('x is 1', x is 1) x = 1000 print('x is 1000', x is 1000)
Output:Warning (from warnings module):
File "C:\Users\djhys\Documents\Python\Musings\junk.py", line 4
print('x is 1000', x is 1000)
SyntaxWarning: "is" with a literal. Did you mean "=="?
>>>
=========== RESTART: C:\Users\djhys\Documents\Python\Musings\junk.py ===========
x is 1 True
x is 1000 True
At least they give you a warning.But the message in that message is a good one. When you can use it, "is" is a better test than "==", and both are bar better than the implicit test in "if x:" If "x" what? If x != 0 and x != None and x != False?