Python中NoneType判断错误排查:Monday.com API数据处理问题
问题:Monday.com API数据解析中None值判断失效
调用Monday.com API获取看板数据并解析JSON时,查询能正常返回正确数据,但在过滤NoneType类型的列值时出现逻辑错误:当"Core Eng (Pts)"列的值为None时,按预期应该进入else分支,实际却触发了if分支。
原代码:
# column-data lstCols = thisItem["column_values"] for thisCol in lstCols: if thisCol["column"]["title"] == "Core Eng (Pts)" and type(thisCol["value"]) is not None: print(f'{cm.OKGREEN}{thisCol["column"]["title"]}{cm.ENDC}') print(f'{cm.OKGREEN}{thisCol["value"]}{cm.ENDC}') print(f'{cm.OKGREEN}{type(thisCol["value"])}{cm.ENDC}') else: print(f'{cm.WARNING}{thisCol["column"]["title"]}{cm.ENDC}') break
运行输出:
Core Eng (Pts) None <class 'NoneType'>
问题原因:
判断条件写错了——type(thisCol["value"]) is not None是在检查值的类型对象是否不等于None,但type(None)返回的是<class 'NoneType'>这个类型实例,它本身不是None,所以这个条件永远为True,导致即使值是None也会进入if分支。
修正方案:
直接判断值本身是否为None,符合PEP8推荐的单例判断规范:
lstCols = thisItem["column_values"] for thisCol in lstCols: if thisCol["column"]["title"] == "Core Eng (Pts)" and thisCol["value"] is not None: print(f'{cm.OKGREEN}{thisCol["column"]["title"]}{cm.ENDC}') print(f'{cm.OKGREEN}{thisCol["value"]}{cm.ENDC}') print(f'{cm.OKGREEN}{type(thisCol["value"])}{cm.ENDC}') else: print(f'{cm.WARNING}{thisCol["column"]["title"]}{cm.ENDC}') break
这样当thisCol["value"]是None时,thisCol["value"] is not None会返回False,条件不满足,就会进入else分支,符合预期逻辑。
内容的提问来源于stack exchange,提问作者Steve Suranie
相关产品推荐
相关产品推荐

