符合 PEP8 的方式对 ['item']['item'] 查找链进行换行



E501:行太长(88个>79个字符(

if true:
if true:
if true:
record = self.content['data']['country_name']['city_name']['postal_address']

我失败的尝试:

if true:
if true:
if true:
record = self.content['data']['country_name'] 
['city_name']['postal_address']

这给出了一个错误:E211"["行:4,列:58前的空白

我正在使用:http://pep8online.com

有几种方法,其中一种可能(我更喜欢(只是添加中间变量(具有一些有意义的名称(。

if True:
if True:
if True:
data = self.content['data']
record = data['country_name']['city_name']['postal_address']

此外,三个嵌套的if可能是一些重构的好候选者,可能带有一些辅助函数,这也会减少行长度。

还有另一种选择:使用括号(PEP8也建议使用反斜杠(

record = (
self.content
['data']
['country_name']
['city_name']
['postal_address']
)

这并不漂亮,但如果你只是想要让自动样式检查器满意的东西。。。

if true:
if true:
if true:
record = self.content['data']['country_name'
]['city_name']['postal_address']

首先,考虑两个if子句是否可以与and运算符合并。

但是,假设每个if子句都有不同的条件,它可能被放置在一个方法中,在该方法中,您可以添加一个或多个将提前退出的保护子句:

def get_content(content):
if not True:
return
if not True:
return
if not True:
return
return content['data']['country_name']['city_name']['postal_address']

record = get_content(content)

您还可以考虑创建中间变量,这可能有助于使其可读性更强且更短。

最新更新