15

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?

3
  • Maybe you will find this SO answer more helpful. Commented Dec 12, 2017 at 18:08
  • 4
    "but for comparison of object to literal, it is identical to ==" - where the heck did you get that idea? Commented Dec 12, 2017 at 18:12
  • @user2357112 I tried it in the prompt and it worked as I expected. But yeah, I didn't read any documentation. Commented Dec 13, 2017 at 10:43

1 Answer 1

27

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
Sign up to request clarification or add additional context in comments.

5 Comments

You shouldn't compare to True or False using is. Source (last bullet point)
@Coal_ good point. Edited and removed those examples.
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
@MichaelGreen then you're not comparing True to True - You are comparing 1 to True which is different.
but 1 == True evaluates to True in Python, which is my point; bool is a subclass of int

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.