24

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,727
  • 8
  • 37
  • 82
  • 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

37

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
  • 34,833
  • 5
  • 57
  • 89
16

Of course you can do it.

type(None)==None.__class__

True
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219