In Python you have the None
singleton, which acts pretty oddly in certain circumstances:
>>> a = None
>>> type(a)
None
is the just a value of types.NoneType
, it's not a type.
And the error is clear enough:
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
From the docs:
None
is the sole value oftypes.NoneType
.None
is frequently used to represent the absence of a value, as when default arguments are not passed to a function.
You can use types.NoneType
>>> from types import NoneType
>>> isinstance(None, NoneType)
True
is
operator also works fine:
>>> a = None
>>> a is None
True
None
is not a type, it is the singleton instance itself - and the second argument of isinstance must be a type, class or tuple of them. Hence, you need to use NoneType
from types.
from types import NoneType
print isinstance(None, NoneType)
print isinstance(None, (NoneType, str, float))
True True
Although, I would often be inclined to replace isinstance(x, (NoneType, str, float))
with x is None or isinstance(x, (str, float))
.
None
is a value(instance) and not a type. As the error message shows, isinstance
expects the second argument to be a type.
The type of None is type(None)
, or Nonetype
if you import it (from types import NoneType
)
Note: the idiomatic way to do the test is variable is None
. Short and descriptive.
You can try:
>>> variable = None
>>> isinstance(variable,type(None))
True
>>> variable = True
>>> isinstance(variable,type(None))
False
isinstance takes 2 arguments isinstance(object, classinfo)
Here, by passing None
you are setting classinfo
to None, hence the error. You need pass in the type.