How to access the NoneType type?
Question:
For example looking at the type of None, we can see that it has NoneType
:
>>> type(None)
NoneType
However a NameError
results when trying to access the NoneType
:
>>> NoneType
NameError: name 'NoneType' is not defined
How can the NoneType
be accessed?
Answers:
Well, in Python 2, or 3.10+, you can import it from the types
module:
from types import NoneType
but it’s not actually implemented there or anything. types.py
just does NoneType = type(None)
. You might as well just use type(None)
directly.
For some reason, they decided to take the types.NoneType
name out in Python 3, before putting it back in 3.10. On versions where the name doesn’t exist, just use type(None)
.
If type(None)
shows NoneType
for you, rather than something like <class 'NoneType'>
, you’re probably on some nonstandard interpreter setup, such as IPython. It’d usually show up as something like <class 'NoneType'>
, making it clearer that you can’t just type NoneType
and get the type.
If the reason you want this is for type annotations, use None
, not types.NoneType
:
def returns_none() -> None:
return None
Static type checkers special-case this use of None
.
As suggested by @dawg in the comments, you can do
if (type(some_object).__name__ == "NoneType"):
# Do some
pass
You can also do
NoneType = type(None)
isinstance(some_object, NoneType)
For example looking at the type of None, we can see that it has NoneType
:
>>> type(None)
NoneType
However a NameError
results when trying to access the NoneType
:
>>> NoneType
NameError: name 'NoneType' is not defined
How can the NoneType
be accessed?
Well, in Python 2, or 3.10+, you can import it from the types
module:
from types import NoneType
but it’s not actually implemented there or anything. types.py
just does NoneType = type(None)
. You might as well just use type(None)
directly.
For some reason, they decided to take the types.NoneType
name out in Python 3, before putting it back in 3.10. On versions where the name doesn’t exist, just use type(None)
.
If type(None)
shows NoneType
for you, rather than something like <class 'NoneType'>
, you’re probably on some nonstandard interpreter setup, such as IPython. It’d usually show up as something like <class 'NoneType'>
, making it clearer that you can’t just type NoneType
and get the type.
If the reason you want this is for type annotations, use None
, not types.NoneType
:
def returns_none() -> None:
return None
Static type checkers special-case this use of None
.
As suggested by @dawg in the comments, you can do
if (type(some_object).__name__ == "NoneType"):
# Do some
pass
You can also do
NoneType = type(None)
isinstance(some_object, NoneType)