Consider this code snippet:
my_string = 'asdf'
print(my_string is 'xfje') #R0123
Pylint returns a recommendation R0123
on the second line, which I was unable to find on the error message wiki. There is a mention of it in this part of the docs, though:
literal-comparison (R0123):
Comparison to literal Used when comparing an object to a literal, which is usually what you do not want to do, since you can compare to a different literal than what was expected altogether.
This explanation is not helpful at all to me. I know that using is
for comparison between two string objects may lead to different results than expected, but for comparison of object to literal, it is identical to ==
. And when using ==
, the error disappears.
Why should I not use is
here?
is
checks that the left hand argument holds the exact same reference as the right hand argument. This is fine for None
which is a singleton, but is usually a bad idea for other types, where multiple instances can have the same logical value.
Consider, e.g. the following example:
>>> my_string = ''.join([c for c in 'xfje'])
>>> print my_string
xfje
>>> print my_string == 'xfje'
True
>>> print my_string is 'xfje'
False