Search code examples
pythonpep8

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


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


Solution

  • 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']
            )