As pointed out by Aaron Hall's comment:
Since you can't subclass
NoneType
and sinceNone
is a singleton,isinstance
should not be used to detectNone
- instead you should do as the accepted answer says, and useis None
oris not None
.
Original Answer:
The simplest way however, without the extra line in addition to cardamom's answer is probably:
isinstance(x, type(None))
So how can I question a variable that is a NoneType? I need to use if method
Using isinstance()
does not require an is
within the if
-statement:
if isinstance(x, type(None)):
#do stuff
Additional information
You can also check for multiple types in one isinstance()
statement as mentioned in the documentation. Just write the types as a tuple.
isinstance(x, (type(None), bytes))
Python 2.7 :
x = None
isinstance(x, type(None))
or
isinstance(None, type(None))
==> True
if variable is None:
...
if variable is not None:
...
Not sure if this answers the question. But I know this took me a while to figure out. I was looping through a website and all of sudden the name of the authors weren't there anymore. So needed a check statement.
if type(author) == type(None):
my if body
else:
my else body
Author can be any variable in this case, and None
can be any type that you are checking for.
It can also be done with isinstance
as per Alex Hall's answer :
>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True
isinstance
is also intuitive but there is the complication that it requires the line
NoneType = type(None)
which isn't needed for types like int
and float
.
I hope this example will be helpful for you)
print(type(None)) # NoneType
So, you can check type of the variable name
# Example
name = 12 # name = None
if type(name) is type(None):
print("Can't find name")
else:
print(name)
Source: Stackoverflow.com