Reputation: 8117
PEP 8 does not seem to prescribe whether line breaking should start from the beginning or from the end of the line, in order to stay within the 79 character limit.
For instance where should I break this line?
long_function_name_1(long_function_name_2(long_function_name_3(long_function_name_4(long_function_name_5(long_function_name_6(long_function_name_7(long_function_name_8(args))))))))
From the beginning?
long_function_name_1(
long_function_name_2(
long_function_name_3(
long_function_name_4(
long_function_name_5(
long_function_name_6(
long_function_name_7(long_function_name_8(args))))))))
Or from the end?
long_function_name_1(long_function_name_2(long_function_name_3(
long_function_name_4(long_function_name_5(long_function_name_6(
long_function_name_7(long_function_name_8(args))))))))
I am particularly interested in the rationale behind the recommendation of one form over the other.
Upvotes: 3
Views: 141
Reputation: 286
I go with the beginning
long_function_name_1(
long_function_name_2(
long_function_name_3(
long_function_name_4(args))))
Indentation makes it clear what function accepts what. If there is more than one argument then they'll form a 'column' (in that case would be better to move the ending parenthesis to a new line too).
Upvotes: 2
Reputation: 43573
First, keep in mind that PEP8 is a guide, not a prescription. Practically speaking Python code is valid as long as it meets the language specification. In practice, I would say "as long as CPython doesn't complain, it's OK".
Use an program like yapf
or black
to format your Python code. That way you don't have to worry about the details. Set up a shortcut in your editor to call the formatter, or call it automatically before you check in a file in your revision control software.
I would suggest setting the acceptable line length for those tools to a value around 90. The outdated 79 character limit in PEP8 comes from low resolution monitors (and going back to hardware terminals and teletypes) that are hardly relevant today. Strictly adhering to this limit in modern Python code with list comprehensions and f-strings can actually make your code less readable. Watch Raymond Hettinger's beyond PEP8. See also his post that was linked in the comments:
PEP 8 is mostly about readability. However, the line length limit often seems to cause less readable code.
With such settings, yapf
makes it into:
long_function_name_1(
long_function_name_2(long_function_name_3(long_function_name_4(args)))
)
Upvotes: 4