简体   繁体   English

PyCharm 类型提示对于嵌套字典不明确

[英]PyCharm Type Hints are ambiguous for nested dicts

I am getting the below warning from Pycharm while trying to access a nested dict.在尝试访问嵌套字典时,我从 Pycharm 收到以下警告。 Here is the code to reproduce the behaviour:这是重现行为的代码:

response = dict()
response['id'] = 'abc'
response['data'] = dict()
response['data']['field'] = {'value': 10,
                               'confidence': None,
                               'source': 'raw',
                               }
value = response['data']['field']['value']

While trying to access the "value", Pycharm complains about the following warning: Expected type 'Union[int, slice]', got 'str' instead在尝试访问“值”时,Pycharm 抱怨以下警告: Expected type 'Union[int, slice]', got 'str' instead

Can someone please help me understand this behaviour?有人可以帮我理解这种行为吗? Thanks!谢谢!

Here is what I'm seeing:这是我所看到的:

Pycharm is only auto typing one or two levels deep. Pycharm 只能自动输入一两层深。 (not sure if there is anything you can do about that part). (不确定您是否可以对那部分做任何事情)。 I also agree (as others have pointed out) that the auto-type hinting doesn't make sense to me either.我也同意(正如其他人指出的那样)自动类型提示对我来说也没有意义。 (likely there is a bug there) (可能那里有一个错误)

However, when I put in my own type hints I can get the warning to go away.但是,当我输入自己的类型提示时,我可以让警告消失。 (currently using 2020.1) (目前使用2020.1)

response: Dict[str, Union[str, Dict[str, Dict[str, Union[int,str,None]]]]] = dict()

Personally I find that super ugly and hard to read.我个人觉得超级丑陋且难以阅读。 Depending on how often these dictionaries are repeated I will sometimes write something like this:根据这些词典的重复频率,我有时会写这样的东西:

T_fieldD = Dict[str, Dict[str, Union[int,str,None]]]
T_respD = Dict[str, Union[str, T_fieldD]]

response: T_respD = dict()

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

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