5

In PEP 8 standard, here, what is the reason for the following recommendation: "Comparisons to singletons like None should always be done with is or is not, never the equality operators."

A-K
  • 16,804
  • 8
  • 54
  • 74
  • For one, it makes the intent more clear. The test `is` for two values *being* the same object, not merely being value-equal. Furthermore, `==` is always true if `is` is true (but the opposite is not always true). – user2864740 Aug 14 '14 at 20:42
  • Also see: [Python None comparison: should I use “is” or ==?](http://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or) – Lukas Graf Aug 14 '14 at 20:43
  • is does an object comparison; you might get inconsistent answers with == – Shawn Aug 14 '14 at 20:44

2 Answers2

0

== and != are equality test, they invoke the __eq__ method to check if the left hand side of the operator represent an object identical to the one on the right hand side.

is and is not are identity tests, they check whether the left hand side and the right hand side of the operator reference the same object.

identity tests are preferred for singleton objects because:

  1. They prevent other object to mimic the singleton one:

    class FakeNone:
        def __eq__(self, other):
            return other is None
    
    print FakeNone() is None        # False
    print FakeNone() == None        # True ... WHAT?
    
  2. They are slightly faster since they do not need to invoke methods.

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
  • 2
    I'm not convinced by reason #1, why would anyone do that without good reason? It's like saying we should use `is` instead of `==` for small integers and interned strings, to prevent someone from mimicking equality of those, which is of course absurd because it is useful that `0 == 0.` etc. – wim Aug 15 '14 at 09:52
-2

Probably performance reasons. is comparison is comparing the id directly without invoking eq of the object.

qihqi
  • 96
  • 2