How to "test" NoneType in python?
So how can I question a variable that is a NoneType?
is operator, like this
if variable is None:
Why this works?
is nottest for object identity:
x is yis true if and only if
yare the same object.
x is not yyields the inverse truth value.
Since there can be only one instance of
is would be the preferred way to check
Hear it from the horse's mouth
Quoting Python's Coding Style Guidelines - PEP-008 (jointly defined by Guido himself),
Comparisons to singletons like
Noneshould always be done with
is not, never the equality operators.
It can also be done with
isinstance as per Alex Hall's answer :
type(None) x = Nonetype(x) == NoneTypeTrueisinstance(x, NoneType)TrueNoneType =
isinstance is also intuitive but there is the complication that it requires the line
NoneType = type(None)
which isn't needed for types like