cmr
cmr

Reputation: 31

Proper line-break formatting according to PEP 8?

According to PEP 8, this is acceptable (and what I have used in the past):

result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)  

My question is, does this also apply to the function definition, so something like:

def some_function_that_takes_arguments(
    a, b, c,
    d, e, f,
):
    return a,b,c,d,e,f  

Another example of what I have done in the past:

if (this_is_one_thing
    and that_is_another_thing
):
    do_something()

I've been doing it this way for a while (for consistency all my lines >79 col are split this way) and am wondering what other people's thoughts are.

Is this clear/nice to look at? Does this adhere to PEP 8?

Upvotes: 2

Views: 8298

Answers (1)

ospahiu
ospahiu

Reputation: 3525

According to this doc on PEP8 it is. Breaking up the function declaration to multi-line is fine as long as the indent level is 4 spaces.

Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent [7]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.

Yes:

# Aligned with opening delimiter. 
foo = long_function_name(var_one, var_two,
                     var_three, var_four)

# More indentation included to distinguish this from the rest. 
def long_function_name(
    var_one, var_two, var_three,
    var_four):
print(var_one)

# Hanging indents should add a level. 
foo = long_function_name(
var_one, var_two,
var_three, var_four)

As a side note if you find your function signature to be getting long due to the number of arguments, consider breaking up your function to more atomic units (therefore adhering to clean code principles).

Upvotes: 2

Related Questions