为什么 Pycharm 的检查员会抱怨“d = {}”?
当使用 d = {}
初始化字典时,Pycharm 的代码检查器会生成一条警告,指出
这个字典创建可以重写为字典文字。
如果我重写它d = dict()
警告就会消失。由于 {}
已经是字典文字,因此我非常确定该消息是错误的。此外,看起来 d = {}
和 d = dict()
都是有效且 Pythonic 的。
这个相关问题似乎得出这样的结论:选择只是风格/偏好的问题: “d = dict()”和“d = {}”之间的差异
为什么 Pycharm 会抱怨 d = {}
?
更新:
Mac 成功了。该警告实际上适用于多行,而不仅仅是标记的那一行。
Pycharm 似乎寻找一系列连续的语句,在其中初始化字典,然后在字典中设置值。例如,这将触发警告:
d = {}
d['a'] = 1
但此代码不会:
d = {}
pass
d['a'] = 1
When initializing a dictionary with d = {}
Pycharm's code inspector generates a warning, saying
This dictionary creation could be rewritten as a dictionary literal.
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.
This related question seems to conclude that the choice is just a matter of style/preference:
differences between "d = dict()" and "d = {}"
Why would Pycharm complain about d = {}
?
UPDATE:
Mac nailed it. The warning actually applied to multiple lines, not just the one that was flagged.
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
But this code will not:
d = {}
pass
d['a'] = 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你的字典声明后面的代码是什么?
如果你有类似的内容,我认为 PyCharm 会触发错误:
正如你可以写的那样
注意:如果你使用函数
字典()。这并不一定意味着 pycharm 认为 dict() 是一个文字。这可能只是意味着它不会抱怨:
What is the code following your dictionary declaration?
I think PyCharm will trigger the error if you have something like:
as you could have written
Note: The fact that the error goes away if you use the function
dict()
. This doesn't necessarily mean that pycharm believesdict()
is a literal. It could just mean that it doesn't complain about it:可以在项目设置或默认设置中禁用此功能。
This can be disabled in the Project Settings or Default Settings.
的多行初始化字典的人
对于那些喜欢(就像我一样)用单个操作而不是像
最后这样
来说: Pycharm 并没有抱怨这一点
for those who like (just like me) to initialize dictionaries with single operation
instead of many lines like
in the end I ended up with this:
Pycharm is not complaining on this
字典可以直接创建,无需先初始化它们,然后重新分配新值。
The dictionary could have been created directly without initialising them first and then reassigning new values.
我遇到的情况是这个警告让我很烦恼。就我而言,我将部分填充为文字,部分填充为函数输出的元组,如下所示:
因此,除非我为 get_other_values 的输出创建临时变量,否则 PEP8 会生成此警告,即使我正在创建带有文字的字典。我无法在文字中分配 c 和 d 键,因为这些值作为元组输出。
I have a situation where this warning is bugging the hell out of me. In my case, I'm populating my dict partially as literals and partially from a tuple output by a function, like so:
So, unless I create interim vars for the output of get_other_values, PEP8 generates this warning even though I'm creating the dict with literals. And I can't assign the c and d keys in the literal, since the values are output as a tuple.