Mypy报错:Optional[Dict[str, str]]的None项无get属性,求解决
解决mypy对字典get方法的类型检查错误
你的代码运行正常,但mypy抛出了类型检查错误,核心原因是:config_dict.get("src")的返回类型被mypy判定为Optional[Dict[str, str]]——因为字典的get方法在找不到对应键时会返回None,mypy严格校验了这种潜在的空值风险,认为你可能调用None.get()。
原代码
from typing import List, Dict, Any def func1(input_list: List[Dict[str, Dict[str, str]]],): for config_dict in input_list: table_1 = ".".join( ( config_dict.get("src").get("db"), # line 6 config_dict.get("src").get("schema"), # line 7 config_dict.get("src").get("table_name"), # line 8 ) ) print(table_1) if __name__ == "__main__": func1( [ { "src": { "db": "db", "schema": "abc", "table_name": "bcd", }, "trgt": { "db": "dd", "schema": "asd", "table_name": "fds", }, } ] )
mypy报错信息
> mypy abc.py abc.py:6: error: Item "None" of "Optional[Dict[str, str]]" has no attribute "get" [union-attr] abc.py:7: error: Item "None" of "Optional[Dict[str, str]]" has no attribute "get" [union-attr] abc.py:8: error: Item "None" of "Optional[Dict[str, str]]" has no attribute "get" [union-attr]
解决办法(保持input_list结构不变)
方案1:直接使用键索引(确保"src"键必存在)
如果能保证每个config_dict中一定包含"src"键,直接用config_dict["src"]替代config_dict.get("src")即可。这种方式会让mypy明确知道该值是确定的Dict[str, str],不会触发空值检查:
from typing import List, Dict, Any def func1(input_list: List[Dict[str, Dict[str, str]]],): for config_dict in input_list: src_config = config_dict["src"] table_1 = ".".join( ( src_config.get("db"), src_config.get("schema"), src_config.get("table_name"), ) ) print(table_1)
方案2:添加类型断言(明确告知mypy"src"不为空)
如果你确定config_dict.get("src")永远不会返回None,但不想修改为键索引,可以用cast做类型断言,强制告诉mypy该值的类型:
from typing import List, Dict, Any, cast def func1(input_list: List[Dict[str, Dict[str, str]]],): for config_dict in input_list: src_config = cast(Dict[str, str], config_dict.get("src")) table_1 = ".".join( ( src_config.get("db"), src_config.get("schema"), src_config.get("table_name"), ) ) print(table_1)
方案3:显式处理空值情况(提升代码健壮性)
如果无法保证"src"键一定存在,最好显式处理None的情况,避免运行时出现AttributeError:
from typing import List, Dict, Any, Optional def func1(input_list: List[Dict[str, Optional[Dict[str, str]]]],): for config_dict in input_list: src_config = config_dict.get("src") if src_config is None: print("缺少必要的src配置") continue table_1 = ".".join( ( src_config.get("db"), src_config.get("schema"), src_config.get("table_name"), ) ) print(table_1)
内容的提问来源于stack exchange,提问作者mindwrapper
相关产品推荐
相关产品推荐

