3

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 ?

Alexander
  • 12,424
  • 5
  • 59
  • 76

2 Answers2

5

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Ah, wrapping the "whole" bit after the `for` does not work because then it includes the `in`. The left-hand (between `for` and `in`) and the right-hand (between `in` and `:` (colon)) sides of the assignment must be separate. Makes sense now. – Kevin Jan 06 '23 at 20:32
  • 1
    Parentheses can only wrap *expressions*, unless otherwise allowed by Python's grammar. Implicit line-joining is a side-effect of parentheses, not the reason they exist. – chepner Jan 06 '23 at 20:36
3
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.

poke
  • 369,085
  • 72
  • 557
  • 602