PyCharm无法识别字典值类型 [英] PyCharm does not recognize dictionary value type

查看:420
本文介绍了PyCharm无法识别字典值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的代码段,其中我将字典值设置为空列表:

I have a simple code snippet where I set dictionary values as empty lists:

new_dict = {}
for i in range(1, 13):
    new_dict[i] = []

现在,如果在下一行的循环内,我将键入new_dict[i]并添加一个点,我希望PyCharm向我显示可用于list的方法列表,但PyCharm无法识别字典值类型在这种简单的情况下:

Now, if inside the loop on the next line I would type new_dict[i] and add a dot, I expect PyCharm to show me a list of methods available for a list, but PyCharm fails to recognize the dictionary value type in this simple case:

为什么会发生,该怎么办?使用PyCharm 2016.1.2,Python 2.7.10.

Why is it happening and what can I do? Using PyCharm 2016.1.2, Python 2.7.10.

作为一种解决方法,我可以显式添加类型提示,通过添加# type: dict[int, list]内联注释,让PyCharm知道new_dict是字典,其中键是整数,值是列表.

As a workaround, I can explicitly add a type hint, letting PyCharm know that new_dict is a dictionary where keys are integers and values are lists by adding a # type: dict[int, list] inline comment:

推荐答案

让我们考虑一个带有变量的稍微复杂的场景:

Lets consider a slightly more complex scenario with a variable:

for i in range(10):
    if i%2:
        x = 3
    else:
        x = "hello"
    x. #type hint for both int and str

在这种情况下,最后一行将为我们提供int s和str s的所有方法,因为PyCharm能够检测到xint还是str

In this case the last line will give us all the methods of ints and strs because PyCharm is able to detect that x will either be an int or a str

现在将所有出现在x上的内容替换为my_dict[i]:

Now replace all the occurences of x with my_dict[i]:

my_dict = {}
for i in range(10):
    if i%2:
        my_dict[i] = 3
    else:
        my_dict[i] = "hello"
    my_dict[i]. #no type hint :(

所有相同的规则都适用于上面,我们知道(并且PyCharm可以弄清楚)my_dict[i]将是intstr.

All of the same rules apply as above, we know (and PyCharm would be able to figure out) that my_dict[i] is either going to be an int or a str.

但是,如果不初始化dict,会发生什么?

However what would you expect to happen if you were not initializing the dict?

def f(my_dict): #or even (my_dict:dict)
    my_dict[1]. #cannot possibly expect a type hint

在这种情况下,没有办法知道字典的值是什么,然后像在您的示例情况下一样,添加一个显式注释:

In this case there is no way to know what the values of the dict are other then adding an explicit annotation just like you would in your example case:

def f(my_dict:"dict[int,list]"):
    my_dict[1]. #get all the list methods

这确实增强了 Python的禅宗中的一些内容:

This really reinforces some lines from The Zen of Python:

显式优于隐式.
可读性计数.
面对模棱两可的想法,拒绝猜测的诱惑.
应该有一种-最好只有一种-显而易见的方法.

Explicit is better than implicit.
Readability counts.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.

(我包括可读性,因为显式类型提示比潜在的隐式分配要容易得多)

(I include readability because the explicit type hint is a lot easier to read then a potentially buried assignment)

这篇关于PyCharm无法识别字典值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆