Skip to main content
 首页 » 编程设计

python之pep8 是否符合长 json 字典查找

2025年05月04日31lovecherry

使用 79 个字符长度,某人将如何制定如下命令:

return method_returning_json()['LongFieldGroup1']['FieldGroup2']['FieldGroup3']['LongValue'] 

如果我将查找移动到下一行,例如:

return method_returning_json()\ 
    ['FieldGroup1']['FieldGroup2']['FieldGroup3']['Value'] 

pep8 提示“[”前有空格,因为有多个制表符。但是,如果我将第二个/第三个/等组移动到换行符,它会做同样的事情。

我知道我可以将 # noqa 标记添加到该行的末尾,但我希望有更好的方法。

请您参考如下方法:

使用出现在括号内的隐式续行:

return (method_returning_json() 
          ['LongFieldGroup1'] 
          ['FieldGroup2'] 
          ['FieldGroup3'] 
          ['LongValue']) 

(您可能需要调整实际缩进以使 pep8 工具满意。)

您甚至可以使用索引括号本身来允许隐式行继续,尽管我并没有发现任何特别可读的变体。

# Legal, but probably not desirable. 
# At the very least, pick one style and be consistent; don't 
# use a variety of options like I show here. 
return method_returning_json()[ 
         'LongFieldGroup1'][ 
         'FieldGroup2'][ 
         'FieldGroup3' 
         ][ 
         'LongValue' 
         ]