0

I was wondering why one should always compare to None using is ?

PEP 8 states:

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

But there is not really an explanation for this guideline ...

Is the only reason 'readability' ? Because that is something very subjective.

andy meissner
  • 1,202
  • 5
  • 15
  • `is` can not be overloaded; `==` and `!=` can. it would be misleading to have `obj == None` to be `True` while `obj is None` is `False`. but as it is possible: with `is` you are always on the safe side. – hiro protagonist Sep 01 '20 at 12:40
  • It is also faster. But it's a *style guide*, it's going to make decisions about readability that not everyone is going to agree with. – juanpa.arrivillaga Sep 01 '20 at 12:43

0 Answers0