Python None comparison: should I use “is” or ==?

后端 未结 3 1530
感情败类
感情败类 2020-11-22 14:10

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

I did a test in the Python shell and determin

3条回答
  •  一个人的身影
    2020-11-22 14:34

    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."

提交回复
热议问题