if A vs if A is not None:

As written in PEP8:

  • 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!


The statement

if A:

will call A.__bool__() (see Special method names documentation), which was called __nonzero__ in Python 2, and use the return value of that function. Here's the summary:

object.__bool__(self)

Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.

On the other hand,

if A is not None:

compares only the reference A with None to see whether it is the same or not.


if x: #x is treated True except for all empty data types [],{},(),'',0 False, and None

so it is not same as

if x is not None # which works only on None

Tags:

Python