proper formatting of python multiline [ for in ] statement

Question:

How should i format a long for in statement in python ?

for param_one, param_two, param_three, param_four, param_five in get_params(some_stuff_here, and_another stuff):

I have found that i can brake a for in statement only with a backslash :

for param_one, param_two, param_three, param_four, param_five 
in get_params(some_stuff_here, and_another_stuff):

But my linter has issues with this formatting , what is a Pythonic way of
formatting statements like this ?

Asked By: Alexander

||

Answers:

all_params = get_params(some_stuff_here, and_another_stuff)
for param_one, param_two, param_three, param_four, param_five in all_params:
    pass

Or you could move the target list inside the loop:

for params in get_params(some_stuff_here, and_another_stuff):
    param_one, param_two, param_three, param_four, param_five = params
    pass

Or combine both.

Answered By: poke

You can take advantage of the implicit line joining inside parentheses (as recommended in PEP-8):

for (param_one, param_two, 
     param_three, param_four, 
     param_five) in get_params(some_stuff_here, 
                               and_another stuff):

(Obviously, you can choose how long to make each line and whether or not you need to include line breaks in each set of parentheses.)


Looking at this 8+ years later, I would break up the long single logical line in the first place, rather than trying to split the whole thing across multiple physical lines. For example (much like @poke does),

for t in get_params(some_stuff_here,
                    and_other_stuff):
    (param_one,
     param_two,
     param_three,
     param_four, param_five) = t
Answered By: chepner
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.