Search code examples
pythonfor-looppep8long-lines

Break up long for statement


I can't find an answer within the PEP 8 style guide. Is there a possibility to break up a long for statement by using round brackets instead of a backslash?

The following will result in a syntax error:

for (one, two, three, four, five in
     one_to_five):
    pass

Solution

  • If the long part is the unpacking, I would just avoid it:

    for parts in iterable:
        one, two, three, four, five, six, seven, eight = parts
    

    Or if it is really long:

    for parts in iterable:
        (one, two, three, four,
         five, six, seven, eight) = parts
    

    If the iterable is a long expression you should put it in a line by itself before the loop:

    iterable = the_really_long_expression(
                   eventually_splitted,
                   on_multiple_lines)
    for one, two, three in iterable:
    

    If both are long then you can just combine these conventions.