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

PEP8-compliant way to line-wrap a chain of ['item']['item'] lookups

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:
            record = self.content['data']['country_name'
                                          ]['city_name']['postal_address']

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

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子句是否可以用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)

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