繁体   English   中英

Python mypy 不兼容类型

[英]Python mypy incompatible types

所以,我有一些代码看起来像这样:

def get_tree(args):
    sensor_ids = argToList(args.get("sensor_ids"))
    process_ids = argToList(args.get("process_ids"))

    all_results = {}

    for sensor_id in sensor_ids:
        sensor_id_str = str(sensor_id)
        for process_id in process_ids:
            process_id_str = str(process_id)
            main_process = query_process(sensor_id_str, process_id_str)

            results = {}
            json_response = main_process.json()

            for vertex in json_response["resources"]:
                if vertex["vertex_type"] == "process":
                    results["main_process"] = {"sensor_id": sensor_id_str,
                                               "process_id": process_id_str,
                                               "properties": vertex["properties"]}

                    for edge in vertex["edges"]:
                        if edge == "child_process":
                            results["child_processes"] = []

MyPy 正在创建此错误,我不确定如何修复,flake 非常高兴:

赋值中的不兼容类型(表达式的类型为“List[]”,目标的类型为“Dict[str, Any]”)[assignment] results["child_processes"] = [] ^

为了原始代码mypy (用 0.950 和 0.961 测试)应该告诉你

“结果”需要类型注释(提示:“ results: Dict[<type>, <type>] =... ”)

所以它可以判断你是否在做正确的事。

使用增强代码,如果您调用reveal_type(results) ,您会看到

a.py:27: note: Revealed type is "builtins.dict[builtins.str, builtins.dict[builtins.str, Any]]"

即根据你对results做的第一个任务,mypy 推断你有一个 dict of dicts,因此,在那里放一个列表是行不通的。

因此,如果您想将results注释为带有字符串键和任意值的基本“包”,

results: Dict[str, Any] = {}

或者如果你想要更严格的输入,请使用TypedDict

class Results(TypedDict):
    child_processes: Optional[List[Any]]  # or be more specific...

results: Results = {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM