How can I split a for statement over multiple lines with Flake8?

Question:

I am currently trying to write a for statement that is over 80 characters long.

for i, (expected, actual) in enumerate(zip_longest(self.__lines, lines)):
    ...
# Note that the line above is 73 characters long. It becomes 81 
# characters long once you put it in a class and a method.
# I did not include the class definition for the sake of the 
# simplicity of the question, but I've needed to add this comment 
# explaining this because people have complained that the line isn't 
# actually > 80 characters long.

In order to satisfy the maximum line length rule in Flake8, I have attempted to split it into multiple lines, but no combination I’ve found appears to satisfy it.

for i, (expected, actual)
    in enumerate(zip_longest(self.__lines, lines)):
    # ^ continuation line with same indent as next logical line - flake8(E125)
        ...
for i, (expected, actual)
in enumerate(zip_longest(self.__lines, lines)):
# ^ continuation line missing indentation or outdented - flake8(E122)
    ...

How can I split my for loop over multiple lines without needing to disable these rules in my config or add a # noqa comment?

Asked By: Miguel Guthridge

||

Answers:

black
suggests you phrase it like this:

        for i, (expected, longish_actual) in enumerate(
            zip_longest(self.__lines, lines)
        ):

In particular,
pep-8
offers this advice:

The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

So imagine that instead of the enumerate we had
catenation of several lists a + b + c + d,
perhaps with longer than single-character names.
The above advice would be followed in this way:

        for x in (a + b
            + c + d):

That is, even though the catenation doesn’t need ( )
parentheses, prefer to wrap the expression with "extra" parens
so the next line will be properly parsed.

Answered By: J_H
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.