Break up long for statement

2.7k views Asked by At

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
2

There are 2 answers

0
Bakuriu On BEST ANSWER

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.

0
shx2 On

Yes, you can use brackets after the in keyword:

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

In your question, as posted, you accidentally dropped the opening bracket, which causes the syntax error you are getting.