首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python3 detect<class 'NoneType'>

Python3 detect<class 'NoneType'>
EN

Stack Overflow用户
提问于 2022-03-09 22:07:42
回答 3查看 224关注 0票数 0

我正在运行一些python3代码,这些代码偶尔会得到一个列表、dict和None。

代码语言:javascript
复制
        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”时除外:

代码语言:javascript
复制
fieldType=
<class 'collections.OrderedDict'>
its not none
#this output works as expected

但是,当fieldType是<class 'NoneType'>时,它报告说它是“没有”

代码语言:javascript
复制
fieldType=
<class 'NoneType'>
its not none

为什么我的代码不能正确识别什么时候一个对象是'None‘类型的?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-03-09 22:15:22

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

看来你想

代码语言:javascript
复制
raw_data[root_key].get("oslc_cm:ChangeRequest") is None

而不是

代码语言:javascript
复制
fieldType is None
票数 1
EN

Stack Overflow用户

发布于 2022-03-09 22:16:20

None != type(None)

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

代码语言:javascript
复制
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')
票数 1
EN

Stack Overflow用户

发布于 2022-03-09 22:13:45

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

代码语言:javascript
复制
if fieldType is None:
    print('its none')
else:
    print('its not none')

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

代码语言:javascript
复制
    fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
    if fieldType is not None:
        print('its not none')
    else:
        print('its none')
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71416542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档