How to "test" NoneType in python?
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
.
if variable is None:
...
if variable is not None:
...
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))
So how can I question a variable that is a NoneType?
Use is
operator, like this
if variable is None:
Why this works?
Since None
is the sole singleton object of NoneType
in Python, we can use is
operator to check if a variable has None
in it or not.
Quoting from is
docs,
The operators
is
andis not
test for object identity:x is y
is true if and only ifx
andy
are the same object.x is not y
yields the inverse truth value.
Since there can be only one instance of None
, is
would be the preferred way to check None
.
Hear it from the horse's mouth
Quoting Python's Coding Style Guidelines - PEP-008 (jointly defined by Guido himself),
Comparisons to singletons like
None
should always be done withis
oris not
, never the equality operators.