Determining a variable's type is NoneType in python

splinter picture splinter · Nov 11, 2016 · Viewed 30.9k times · Source

I would like to check if a variable is of the NoneType type. For other types we can do stuff like:

    type([])==list

But for NoneType this simple way is not possible. That is, we cannot say type(None)==NoneType. Is there an alternative way? And why is this possible for some types and not for others? Thank you.

Answer

Alex Hall picture Alex Hall · Nov 11, 2016

NoneType just happens to not automatically be in the global scope. This isn't really a problem.

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

In any case it would be unusual to do a type check. Rather you should test x is None.