Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining a variable's type is NoneType in python [duplicate]

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.

like image 370
splinter Avatar asked Nov 11 '16 17:11

splinter


People also ask

How do you check if something is NoneType in Python?

To check whether a variable is None or not, use the is operator in Python. With the is operator, use the syntax object is None to return True if the object has the type NoneType and False otherwise.

Is NoneType the same as null?

Null Vs None in Python None – None is an instance of the NoneType object type. And it is a particular variable that has no object value. Null – There is no null in Python, we can use None instead of using null values.

How do I fix NoneType in Python?

The error “TypeError: 'NoneType' object is not iterable” occurs when you try to iterate over a NoneType object. Objects like list, tuple, and string are iterables, but not None. To solve this error, ensure you assign any values you want to iterate over to an iterable object.

Is NoneType a type?

What Is NoneType in Python? NoneType in Python is a data type that simply shows that an object has no value/has a value of None . You can assign the value of None to a variable but there are also methods that return None .


2 Answers

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.

like image 75
Alex Hall Avatar answered Sep 22 '22 23:09

Alex Hall


Of course you can do it.

type(None)==None.__class__

True
like image 36
Jean-François Fabre Avatar answered Sep 25 '22 23:09

Jean-François Fabre