Mypy未识别类型判断条件引发类型检查报错求助
解决Mypy无法识别字典值类型判断的问题
问题原因
你的字典COL的值包含两种类型:list[str]和dict[str, str],Mypy默认会把值的类型推断为Collection[str](列表和字典都属于这个抽象类型),但Collection没有keys()方法,因此触发报错。另外,直接多次访问COL[table_name]时,Mypy无法关联不同访问操作的类型一致性,导致类型判断逻辑不被识别。
解决方案
1. 添加精确的类型注解
给COL指定明确的联合类型,告诉Mypy字典的值要么是字符串列表,要么是字符串键值对的字典:
from typing import Union, Dict, List COL: Dict[str, Union[List[str], Dict[str, str]]] = { "ABC": [ "col1", "col2", "col3", ], "BBC": [ "col1", "col2", "col3", ], "XYZ": { "col1": "c1", "col2": "c2", "col3": "c3", }, }
2. 将字典值赋值给变量再判断
把COL[table_name]存入一个变量,让Mypy能跟踪该变量的类型,从而正确识别isinstance的类型分支:
for table_name in COL: cols = COL[table_name] result = list(cols.keys()) if isinstance(cols, dict) else cols
修改后的完整代码
from typing import Union, Dict, List COL: Dict[str, Union[List[str], Dict[str, str]]] = { "ABC": [ "col1", "col2", "col3", ], "BBC": [ "col1", "col2", "col3", ], "XYZ": { "col1": "c1", "col2": "c2", "col3": "c3", }, } for table_name in COL: cols = COL[table_name] result = list(cols.keys()) if isinstance(cols, dict) else cols
这样修改后,Mypy就能正确识别类型判断逻辑,不会再报错,同时代码可读性也得到提升。
内容的提问来源于stack exchange,提问作者Kingston X
相关产品推荐
相关产品推荐

