Search code examples
pythonpython-3.xpython-2.7standardspep8

The proper way to compare a variable with None


The commom way to test variable for NoneType is checking if it is referring to None singletone:

test_var is None

This approach is recommended as the only way to check for None according to PEP-8:

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

Although sometimes I find the following test in different sources:

isinstance(test, type(None))

This way looks OK, but I can't quite figure out why simple and readable construction may be replaced with isinstance. Is it more useful for some cases or maybe referred to codestyle?

UPD: the only NoneType checking with isinstance I find really useful (so far):

isinstance(None, (NoneType, str, float))

Solution

  • No, there is never a reason to use that construct.

    You can't subclass NoneType. The only object that would ever pass that test is the None singleton. That line was probably written by someone that didn't know this and thought they needed to test for subclasses too.