问题描述
当用 d = {}
初始化字典时,Pycharm 的代码检查器会生成一个警告,说
When initializing a dictionary with d = {}
Pycharm's code inspector generates a warning, saying
这个字典创建可以重写为字典文字.
如果我重写它 d = dict()
警告就会消失.由于 {}
已经 is 字典文字,我很确定该消息是错误的.此外,似乎 d = {}
和 d = dict()
都是有效的和 Pythonic 的.
If I rewrite it d = dict()
the warning goes away. Since {}
already is a dictionary literal, I'm pretty sure the message is erroneous. Furthermore, it seems like both d = {}
and d = dict()
are valid and Pythonic.
这个相关问题似乎得出结论,选择只是风格/偏好问题:d = dict()"之间的差异;和d = {}"
This related question seems to conclude that the choice is just a matter of style/preference:differences between "d = dict()" and "d = {}"
为什么 Pycharm 会抱怨 d = {}
?
Why would Pycharm complain about d = {}
?
更新:
Mac 搞定了.警告实际上适用于多行,而不仅仅是被标记的那一行.
Mac nailed it. The warning actually applied to multiple lines, not just the one that was flagged.
Pycharm 似乎寻找一系列连续语句,您可以在其中初始化字典,然后在字典中设置值.例如,这将触发警告:
Pycharm seems to look for a sequence of consecutive statements where you initialize a dictionary and then set values in the dictionary. For example, this will trigger the warning:
d = {}
d['a'] = 1
但是这段代码不会:
d = {}
pass
d['a'] = 1
推荐答案
你的字典声明下面的代码是什么?
我认为 pycharm 会触发错误,如果您有以下情况:
I think pycharm will trigger the error if you have something like:
dic = {}
dic['aaa'] = 5
正如你所写的
dic = {'aaa': 5}
顺便说一句:如果您使用该函数,错误消失的事实并不一定意味着 pycharm 相信 dict()
是一个文字.这可能只是意味着它不会抱怨:
BTW: The fact that the error goes away if you use the function doesn't necessarily mean that pycharm believes dict()
is a literal. It could just mean that it doesn't complain for:
dic = dict()
dic['aaa'] = 5
HTH!
这篇关于为什么 Pycharm 的检查员会抱怨“d = {}"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!