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

Viewed 92

E501: line too long (88 > 79 characters)

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

My failed attempt:

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

This is giving an error: E211 whitespace before '[' line: 4, column: 58

I'm using: http://pep8online.com

3 Answers

There are several ways, one possibility (that I would prefer) is just adding intermediate variables (with some meaningful names).

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

Also, three nested ifs are probably a good candidate for some refactoring, maybe with some auxiliary functions, that would also reduce the line length.

Yet another alternative: use parentheses (recommended by PEP8 over the backslash too)

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

It's not pretty, but if you just want something that makes the automated style checker happy...

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

First of all, consider if two if clauses can be merged with the and operator.

But, assuming each if clause will have a different condition, it may be placed inside a method where you may add one or several guard clauses that will exit early:

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)

You may also consider to create intermediate variables, that may help making it both more readable and shorter.

Related