13

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?

Community
  • 1
  • 1
iFreilicht
  • 13,271
  • 9
  • 43
  • 74
  • Maybe you will find this SO [answer](https://stackoverflow.com/questions/2209755/python-operation-vs-is-not) more helpful. – kingJulian Dec 12 '17 at 18:08
  • 4
    "but for comparison of object to literal, it is identical to `==`" - where the heck did you get that idea? – user2357112 Dec 12 '17 at 18:12
  • @user2357112 I tried it in the prompt and it worked as I expected. But yeah, I didn't read any documentation. – iFreilicht Dec 13 '17 at 10:43

1 Answers1

25

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • You shouldn't compare to `True` or `False` using `is`. [Source](https://www.python.org/dev/peps/pep-0008/#programming-recommendations) (last bullet point) – Daniel Dec 12 '17 at 19:21
  • @Coal_ good point. Edited and removed those examples. – Mureinik Dec 12 '17 at 20:49
  • Daniel, I'm not entirely sure that is the case - checking `x is True` assures that `x` doesn't pass the check of `x == True` with `x = 1` – Michael Green Nov 07 '19 at 17:23
  • @MichaelGreen then you're not comparing `True` to `True` - You are comparing `1` to `True` which is different. – vidstige Oct 18 '21 at 13:57
  • but `1 == True` evaluates to `True` in Python, which is my point; `bool` is a subclass of `int` – Michael Green Oct 18 '21 at 18:37