Checking whether type is None

Chris Angelico rosuav at gmail.com
Tue Jul 24 19:32:27 EDT 2018


On Wed, Jul 25, 2018 at 9:18 AM, Rob Gaddi
<rgaddi at highlandtechnology.invalid> wrote:
> On 07/24/2018 01:07 PM, Chris Angelico wrote:
>>
>> On Wed, Jul 25, 2018 at 5:33 AM, Tobiah <toby at tobiah.org> wrote:
>>>
>>> Consider:
>>>
>>>          >>> type({}) is dict
>>>          True
>>>          >>> type(3) is int
>>>          True
>>>          >>> type(None) is None
>>>          False
>>>
>>> Obvious I guess, since the type object is not None.
>>> So what would I compare type(None) to?
>>>
>>>          >>> 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
>>>
>>>
>>> I know I ask whether:
>>>
>>>          >>> thing is None
>>>
>>> but I wanted a generic test.
>>> I'm trying to get away from things like:
>>>
>>>          >>> type(thing) is type(None)
>>>
>>> because of something I read somewhere preferring
>>> my original test method.
>>
>>
>> There is nothing more generic in a type test than in simply saying "is
>> None". There are no other instances of NoneType. Don't try
>> type-checking None; just check if the object is None.
>>
>> ChrisA
>>
>
> I suppose one valid usage would be this sort of thing:
>
> fn = {
>     int: dispatchInt,
>     str: dispatchStr,
>     list: dispatchList,
>     type(None): dispatchNone
> }[type(x)]
> fn(x)
>

True, but that would be useful only in a very few situations, where
you guarantee that you'll never get any subclasses. So if you're
walking something that was decoded from JSON, and you know for certain
that you'll only ever get those types (add float to the list and it's
basically covered), then yes, you might do this; and then I would say
that using "type(None)" is the correct spelling of it.

ChrisA



More information about the Python-list mailing list