Checking whether type is None

Steven D'Aprano steve+comp.lang.python at
Tue Jul 24 19:02:11 EDT 2018

On Tue, 24 Jul 2018 12:33:27 -0700, Tobiah wrote:

> So what would I compare type(None) to?

Why would you need to? The fastest, easiest, most reliable way to check 
if something is None is:

    if something is None

> 	>>> type(None)
> 	<type 'NoneType'>
> 	>>> type(None) is NoneType
> 	Traceback (most recent call last):
> 	  File "<stdin>", line 1, in <module>
> 	NameError: name 'NoneType' is not defined

You can do:

    from types import NoneType

or if you prefer:

    NoneType = type(None)

but why bother?

> I know I ask whether:
> 	>>> thing is None
> but I wanted a generic test.

That *is* a generic test.

> I'm trying to get away from things like:
> 	>>> type(thing) is type(None)

That is a good move.

> because of something I read somewhere preferring my original test
> method.

Oh, you read "something" "somewhere"? Then it must be good advice!


Writing code like:

    type(something) is dict

was the standard way to do a type check back in the Python 1.5 days. 
That's about 20 years ago now. These days, that is rarely what we need 

The usual way to check a type is:

    isinstance(something, dict)

but even that should be rare. If you find yourself doing lots of type 
checking, using isinstance() or type(), then you're probably writing 
slow, inconvenient Python code.

Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

More information about the Python-list mailing list