Why does Pycharm's inspector complain about “d = {}”?

前端 未结 5 713
刺人心
刺人心 2020-12-23 12:53

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

This dictionary creation could be rewrit

相关标签:
5条回答
  • 2020-12-23 13:19

    This can be disabled in the Project Settings or Default Settings.

    • Navigate to Settings -> Inspections -> Python
    • Uncheck "Dictionary creation could be rewritten by dictionary literal"
    0 讨论(0)
  • 2020-12-23 13:25

    What is the following code to your dictionary declaration?

    I think pycharm will trigger the error if you have something like:

    dic = {}
    dic['aaa'] = 5
    

    as you could have written

    dic = {'aaa': 5}
    

    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!

    0 讨论(0)
  • 2020-12-23 13:28

    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:

    def get_other_values():
        return 3, 4
    
    foo = {
        "a": 1,
        "b": 2
    }
    foo["c"], foo["d"] = get_other_values()
    

    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.

    0 讨论(0)
  • 2020-12-23 13:30
    mydict = {
      a: 5,
      b:z+c/2
    }
    

    The dictionary could have been created directly without initialising them first and then reassigning new values.

    0 讨论(0)
  • 2020-12-23 13:31

    for those who like (just like me) to initialize dictionaries with single operation

    d = {
      'a': 12,
      'b': 'foo',
      'c': 'bar'
    }
    

    instead of many lines like

    d = dict()
    d['a'] = 12
    d['b'] = ....
    

    in the end I ended up with this:

    d = dict()
    d.update({
      'a': 12,
      'b': 'foo',
      'c': 'bar'
    })
    

    Pycharm is not complaining on this

    0 讨论(0)
提交回复
热议问题