Python3 检测不到<class 'NoneType'>

Python3 cant detect<class 'NoneType'>

我是运行一些python3代码,偶尔会得到一个列表、字典和None。

        fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
        print('fieldType=')
        print(fieldType)
        if fieldType is None:
            print('its none')
        else:
            print('its not none')

这适用于所有情况,除非 fieldType 为 'None':

fieldType=
<class 'collections.OrderedDict'>
its not none
#this output works as expected

但是当 fieldType 为 <class 'NoneType'> 时,它报告为 'not none'

fieldType=
<class 'NoneType'>
its not none

为什么我的代码无法正确识别对象的类型 'None'?

这是一个常见的错误。测试值是否为 None 的正确方法是使用 is 或 is not,而不是使用相等性测试:

if fieldType is None:
    print('its none')
else:
    print('its not none')

get() 方法 returns None(因此计算结果为 False)当字典中没有项目时。这意味着您将通过使用 if not raw_data[root_key].get("oslc_cm:ChangeRequest") 获得相同的结果:这意味着“如果 oslc_cm:ChangeRequest in raw_data[root_key] 没有条目”。因此,您可以这样编写代码:

    fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
    if fieldType is not None:
        print('its not none')
    else:
        print('its none')

fieldType<class 'NoneType'>,不同于None。它永远不可能是 None,因为 type 总是 returns 某种类型。

看起来你想要

raw_data[root_key].get("oslc_cm:ChangeRequest") is None

而不是

fieldType is None

None != type(None)

type(None) 是一个 <class 'type'> 对象。在 python 中检查变量类型的正确方法是使用 isinstance()。那么您的代码将如下所示:

NoneType = type(None)
fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
print('fieldType=')
print(fieldType)
if isinstance(fieldType, NoneType):
    print('its none')
else:
    print('its not none')