Pylint 抱怨用 'is' 将字符串与文字进行比较

Pylint complains about comparing a string to a literal with 'is'

考虑这个代码片段:

my_string = 'asdf'
print(my_string is 'xfje') #R0123

Pylint returns 第二行的推荐 R0123,我在 error message wiki. There is a mention of it in this part of the docs 上找不到,但是:

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.

这个解释对我一点帮助都没有。我知道使用 is 比较两个字符串对象可能会导致与预期不同的结果,但是对于对象与文字的比较,它与 == 相同。而当使用==时,错误消失。

为什么我不能在这里使用 is

is 检查左手参数与右手参数 完全相同的引用 。这对于单例的 None 很好,但对于其他类型通常是个坏主意,因为多个实例可以具有相同的逻辑值。

考虑,例如以下示例:

>>> my_string = ''.join([c for c in 'xfje'])
>>> print my_string
xfje
>>> print my_string == 'xfje'
True
>>> print my_string is 'xfje'
False