Python None 比较:我应该使用“is”还是 ==?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14247373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:51:55  来源:igfitidea点击:

Python None comparison: should I use "is" or ==?

pythoncomparisonnonetype

提问by Clay Wardell

My editor warns me when I compare my_var == None, but no warning when I use my_var is None.

我的编辑器在我比较时会警告我my_var == None,但当我使用my_var is None.

I did a test in the Python shell and determined both are valid syntax, but my editor seems to be saying that my_var is Noneis preferred.

我在 Python shell 中进行了测试并确定两者都是有效的语法,但我的编辑器似乎在说这my_var is None是首选。

Is this the case, and if so, why?

是这样吗,如果是,为什么?

采纳答案by mgilson

Summary:

概括:

Use iswhen you want to check against an object's identity(e.g. checking to see if varis None). Use ==when you want to check equality(e.g. Is varequal to 3?).

使用is时要核对对象的身份(如检查,看看是否varNone)。使用==时要检查的平等(例如是var等于3?)。

Explanation:

解释:

You can have custom classes where my_var == Nonewill return True

您可以拥有自定义类my_var == None将返回True

e.g:

例如:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

ischecks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalentobjects)

is检查对象标识。只有 1 个对象None,所以当你这样做时my_var is None,你是在检查它们是否实际上是同一个对象(不仅仅是等效的对象)

In other words, ==is a check for equivalence (which is defined from object to object) whereas ischecks for object identity:

换句话说,==是检查等价性(从对象到对象定义),而is检查对象身份:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

回答by user4815162342

isis generally preferred when comparing arbitrary objects to singletons like Nonebecause it is faster and more predictable. isalways compares by object identity, whereas what ==will do depends on the exact type of the operands and even on their ordering.

is在将任意对象与单例进行比较时通常首选,None因为它更快且更可预测。is总是按对象标识进行比较,而==将做什么取决于操作数的确切类型,甚至取决于它们的顺序。

This recommendation is supported by PEP 8, which explicitly statesthat "comparisons to singletons like None should always be done with isor is not, never the equality operators."

这个建议得到了PEP 8 的支持,它明确指出“与像 None 这样的单例的比较应该总是用isor完成is not,永远不要使用相等运算符。”

回答by Thorsten Kranz

PEP 8 defines that it is better to use the isoperator when comparing singletons.

PEP 8 定义is在比较单例时最好使用运算符。