简体   繁体   English

mypy和嵌套dict理解

[英]mypy and nested dict comprehension

I'm definitely not an expert of mypy, but there's an error that I'm really not understanding. 我绝对不是mypy的专家,但是我确实不了解一个错误。

Let's say that I have this dictionary and I want to parse it and create another one through a dict comprehension. 假设我有这本字典,我想解析它并通过dict理解创建另一个字典。

my_dict = {
    'type1': {
        'category1': [
            'subcategory1',
            'subcategory2',
        ],
    },
    'type2': {
        'category2': [
            'subcategory3',
        ],
        'category3': [],
    },
}

The dict comprehension: 字典理解:

new_dict = {
    subcategory: {
        'category': category,
        'type': type,
    }
    for type, categories in my_dict.items()
    for category, subcategories in categories.items()
    for subcategory in subcategories
}

and the expected output: 和预期的输出:

{
    'subcategory1': {
        'category': 'category1',
        'type': 'type1'
    },
    'subcategory2': {
        'category': 'category1',
        'type': 'type1'
    },
    'subcategory3': {
        'category': 'category2',
        'type': 'type2'
    }
}

mypy in this situation complains because of the empty category3 , but with an error message ( 'error:"object" has no attribute "items"' ) that refers to the previous line. 在这种情况下,mypy会因为category3为空而抱怨,但出现了一条错误消息( 'error:"object" has no attribute "items"' ),该消息指向上一行。

Any suggestion? 有什么建议吗?

Thanks in advance 提前致谢

The issue is mypy is unable to infer the type of my_dict -- it's too complicated for mypy to naturally infer the type. 问题是mypy无法推断my_dict的类型-对于mypy而言自然无法推断类型太复杂。

You can confirm for yourself by adding the line reveal_type(my_dict) before running mypy. 您可以通过在运行mypy之前添加reveal_type(my_dict)行来自己确认。 (Mypy special-cases that function name to help with debugging). (Mypy特有的函数名称有助于调试)。 The inferred type ended up being Dict[str, object] , or something to that effect. 推断的类型最终是Dict[str, object]或类似的东西。

You can fix this by explicitly giving my_dict a type. 您可以通过显式my_dict类型来解决此问题。 If you're using Python 3.6+, you can use the new variable annotation syntax to do so, like so: 如果您使用的是Python 3.6+,则可以使用新的变量注释语法来这样做,如下所示:

from typing import Dict, List

my_dict: Dict[str, Dict[str, List[str]]] = { ... }

If you're using earlier versions of Python, annotate the variable using the comment-based syntax. 如果您使用的是Python的早期版本,请使用基于注释的语法对变量进行注释。

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

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