Ptyhon 中使用 is None 而不是 ==None 问题

首先需要区分 Python 中is==的区别:


看下面的 回答

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

This recommendation is supported by PEP 8, which explicitly states that “comparisons to singletons like None should always be done with is or is not, never the equality operators.”

通常,在将任意对象与None之类的单个对象进行比较时首选is,因为它更快且更可预测。 is总是根据对象标识进行比较,而==的作用取决于运算对象的确切类型,甚至取决于它们的顺序。
PEP 8 支持此建议,该声明明确指出“与单例的比较(如None,应该始终使用isnot进行比较,永远不要使用相等运算符进行比较)”。

>>> a = timeit.timeit("1 is None", number=10000000) # 0.6208912429997326

>>> b = timeit.timeit("1 == None", number=10000000) # 0.9341017190004095

>>> a /b



Python: “is None” vs “==None” | Jared Grubb
python - What is the difference between “ is None “ and “ ==None “ - Stack Overflow