25

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.

3
  • 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. Commented Nov 11, 2016 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. Commented Nov 11, 2016 at 17:56
  • @ZeroPiraeus see above in case you weren't notified. Commented Nov 11, 2016 at 17:57

2 Answers 2

38

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I suppose both this solution and the solution of @JeanFrancoisFabre do the job. Do we have some reason to prefer one of them over the other (speed,style,etc.)?
@splinter not that I know of.
17

Of course you can do it.

type(None)==None.__class__

True

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.