Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a time when the `is` operator can return false with two similar strings in Python? [duplicate]

I had some code that I was editing to make it more understandable at a glance and I thought I should change all the char=="|" to char is "|". I know that it looks like I'm dumbing it down too much but it does look better. Anyway, I decided to pycheck one last time and I got this warning:

Warnings...

test.py:7: Using is |, may not always work
Processing module test (test.py)...

For the life of me, I can't imagine a situation when "|" is "|" will return False unless you start venturing into multibyte character encodings, CJK characters and the like, if I'm not wrong. Is there some other situation that I've missed?

like image 428
Plakhoy Avatar asked Nov 29 '22 12:11

Plakhoy


1 Answers

== will check if values on both the sides are equal, but is will check if both the variables are pointing to the same reference. So, they both are for entirely different purposes. For example,

a = "aa"
b = "aa"
print a, b, id(a), id(b)
print a == b
print a is b

Output on my machine

aa aa 140634964365520 140634964365520
True
True

since a and b are pointing to the same String data (strings are immutable in Python), python optimizes to use the same object. That is why is and == both are returning True. where as

a = "aa"
b = "aaa"[:2]
print a, b, id(a), id(b)
print a == b
print a is b

Output on my machine

aa aa 139680667038464 139680667014248
True
False

Though a and b have the same data (equal), in the memory they are stored in different places (different references or two different objects).

So, never use is operator to check for equality.

like image 75
thefourtheye Avatar answered May 17 '23 11:05

thefourtheye