Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pylint complains about comparing a string to a literal with 'is' [duplicate]

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?

like image 559
iFreilicht Avatar asked Dec 12 '17 18:12

iFreilicht


People also ask

How do you check if two strings are identical in python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

What is literal comparison?

Description: 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.

Can you use == on strings in python?

Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.


1 Answers

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
like image 101
Mureinik Avatar answered Sep 22 '22 01:09

Mureinik