为什么 Pycharm 的检查器会抱怨“d = {}"? [英] Why does Pycharm's inspector complain about "d = {}"?

查看:27
本文介绍了为什么 Pycharm 的检查器会抱怨“d = {}"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 d = {} 初始化字典时,Pycharm 的代码检查器会生成一个警告,说

When initializing a dictionary with d = {} Pycharm's code inspector generates a warning, saying

这个字典创建可以重写为字典文字.

This dictionary creation could be rewritten as a dictionary literal.

如果我重写它 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() 是文字.这可能只是意味着它不会抱怨:

Note: 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

这篇关于为什么 Pycharm 的检查器会抱怨“d = {}"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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