15

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.

splinter
  • 3,327
  • 6
  • 33
  • 74
  • 2
    Just use `x is None`. There is no advantage whatsoever to checking the type, as there will never under any circumstances be any object other than `None` of type `NoneType`. – Zero Piraeus Nov 11 '16 at 17:47
  • 1
    I think the idea is to be able to pass `type(x) == y` for any x,y, not to add a special case for `x is None`. Note: you can also do `x == None`. – Jean-François Fabre Nov 11 '16 at 17:56
  • @ZeroPiraeus see above in case you weren't notified. – Alex Hall Nov 11 '16 at 17:57

2 Answers2

22

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.

Alex Hall
  • 33,530
  • 5
  • 49
  • 82
15

Of course you can do it.

type(None)==None.__class__

True
Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195